Java interview programming question set-3

1) Fibonacci in Java:
The input will be number n and the output should be sum for 0 to n. for example
for n =4 the result should be 0+1+2+3+4 = 10
public class FibonacciNumber {
public static int fibonacci(int n) {
   if (n < 2) {
    return n;
   }
   else {
    return fibonacci(n-1)+fib(n-2);
   }
  }
}
view rawFibbonacci.java hosted with ❤ by GitHub

2) String Reverse
The input String "abcde" should return "edcba".
public reverse(String word) {
char[] chs = word.toCharArray();
int i=0, j=chs.length-1;
while (i < j) {
 // swap chs[i] and chs[j]
  char t = chs[i];
  chs[i] = chs[j];
  chs[j] = t;
  i++; j--;
 }
}

//Another way using java utility.
import org.apache.commons.lang.StringUtils;
String reverseWords(String sentence) {
  return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' ');
}
view rawreverseString.java hosted with ❤ by GitHub

3) Reversing a linked list in Java
Here is example of revering the linked list in java using recursive function:
public class ListNode {
 String data = "";
 ListNode next = null;
public ListNode(String data, ListNode node) {
 this.data = data;
 this.next = node;
}
// reverse
public static ListNode reverse (ListNode list){
 if (list == null) return null;
 if (list.next == null) return list;
 ListNode secondElem = list.next;
 list.next = null;
 ListNode reverseRest = reverse(secondElem);
 secondElem.next = list;
 return reverseRest;
}
public static void main(String[] args) {
  ListNode node3= new ListNode ("node3",null);
  ListNode node2= new ListNode ("node2",node3);
  ListNode node1= new ListNode ("node1",node2);
  System.out.println(" Last Item : "+node1.next.next.data+"\n");
  ListNode reverseList = ListNode.reverse(node1);
  System.out.println("First Item "+reverseList.data);
 }
} 
view rawlistNode.java hosted with ❤ by GitHub

4) Find the missing number in Java
You have an array of numbers from 1 to 100 (both inclusive). The size of the array is 100. The numbers are randomly added to the array, but there is one random empty slot in the array. What is the quickest way to find that slot as well as the number that should be put in the slot?
Try it for practice. please suggest the answer .
[Trick sum of n numbers is n*(n+1)/2]
import java.util.*;
public class MissingNumber {
public static void main(String...strings){
  Set numberSet = new HashSet();
// Max number in the sequence 
int k = 50; 
// put the numbers
for(int i=0;i<=50;i++){
numberSet.add(i);
}
// Remove random number
int i =  (new Random()).nextInt(50);
System.out.println(" Removing number -->"+i);
numberSet.remove(i);
// find the current sum
int sum =0;
for(int m : numberSet){
sum= sum +m;
}
// Find the missing number
int l = ((k)*((k+1))/2)- sum;
System.out.println(" Missing number -->"+l);
}
}
view rawMissingNumber.java hosted with ❤ by GitHub


5) Write a substring function in Java
String test= "AA BB CC BB BB CC BB";
String[]{"BB", "CC", "AA"}
Result shd be BB=4; CC=2 and AA=1
Since B occurred 4 times C did 2 times and A only 1 time.
This basic problem can be asked in different ways like, You have multiple words in new paper and find out the frequency of words in one page of news paper?
public static String[] sortingData(String data) {
  String[] strings = data.split(" ");
  // Finding distinct values
  HashMap map = new HashMap();
  for (String s : strings) {
    Integer i = map.get(s);
    if (i != null) {
      map.put(s, i+1);
    } else {
    map.put(s, 1);
  }
}
// Ordering using Collections
TreeMap sort = new TreeMap(Collections.reverseOrder());
 for (Entry e : map.entrySet()) {
  sort.put(e.getValue(), e.getKey()); 
 }
  return sort.values().toArray(new String[0]);
}
view rawsortingString.java hosted with ❤ by GitHub

6) Reverse a String in Java
Reverse the String by java function without recursion and with recursion
//Reverse the String by java function without recursion
public static String reverseString(String str){
 if(str==null || str.length()==1) 
   return str;
 int i = str.length();
 char[] reverse = new char[i];
 for(int j=0;j;j++)
   reverse[j]= str.charAt(i-j-1);
  }
  return new String(reverse);
}

//Reverse the String by java function  with Recursive Function
public static String reverse(String str) {
 if ((null == str) || (str.length() <= 1)) {
  return str;
 }
    return reverse(str.substring(1)) + str.charAt(0);
}
view rawStringReverse.java hosted with ❤ by GitHub

7) Find one string inside another in Java
We can use String.indexOf( subString ) and it will return the first index of substring;
for Last Index : lastIndexOf(String str)

8) Algo for finding largest number in Array of Integer
Easy one, Check the integer one by one and find the largest number.

9) Java Runtime method invocation question:
Example : Tell the output of this
class Base {
    protected int i;

Base() {
add(1);
}

void add(int v) {
i += v;
}
}

class Extension extends Base {
Extension() {
add(1);
}

void add(int v) {
i += v * 2;
}
}

public class Example {
public static void main(String[] args) {
System.out.println(" " + bogo(new Extension()));
}

static int bogo(Base b) {
return b.add(8);
}
}
view rawRuntimeMethodBinding.java hosted with ❤ by GitHub
Answer is : 20 .

10) Suppose you have a large file with lots of words. How would you find the unique words and their count? What kind of data structure u will use? What will be the time complexity and space complexity?
We need to take care of two things counting the words and second duplicate. the best performance will be using hash function.
import java.util.*;
public class Freq {
    public static void main(String[] args) {
        Map m = new HashMap();
      // Initialize frequency table from command line
        for (String a : args) {
            Integer freq = m.get(a);
            m.put(a, (freq == null) ? 1 : freq + 1);
        }
       System.out.println(m.size() + " distinct words:");
       System.out.println(m);
    }
}
view rawWordFrequency.java hosted with ❤ by GitHub


11) A train is one mile long. It travels at the rate of one mile a minute through a tunnel which is also one mile long. Can you say how long it will take for the train to pass completely through the tunnel? 

Answer : 2 minutes

it will take two minutes if you count the time for it to completely pass through the tunnel. One minute to pass through the tunnel and another one minute to drag itself out of the tunnel completely so two minutes nice question though well logical.



12) Convert String = "98989" into an integer without using any library functions in java.
Give fastest way to do it and explain why your method is best.
// converting string to number using ascii code
// converting string to number using ascii code
public static int convertStringToInt(String num){
int result=0;
int zeroAscii=48;
int nineAscii=57;
for(char c: num.toCharArray()){
  if(c>=zeroAscii && c<=nineAscii){
  result=result*10+(c-zeroAscii);
 }else
  return -1;
 }
return result;
}
view rawcharToNumber.java hosted with ❤ by GitHub


13) Write a program to shuffle a deck of 52 cards and shuffle them equally to 4 players.

package com.learning.puzzle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/*
 * Write the code to shuffle a deck of 52 cards,
 * and shuffle them equally to 4 players
 */
class Card {
  public enum Rank {
DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank rank() {
return rank;
}
public Suit suit() {
return suit;
}
public String toString() {
return rank + " of " + suit;
}
private static final List<Card> protoDeck = new ArrayList<Card>();
// Initialize prototype deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
protoDeck.add(new Card(rank, suit));
}
public static ArrayList<Card> newDeck() {
return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
}
}
public class RandomCards {
private Map<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
public RandomCards() {
}
public static void main(String[] args) {
ArrayList<Card> player1 = new ArrayList<Card>();
ArrayList<Card> player2 = new ArrayList<Card>();
ArrayList<Card> player3 = new ArrayList<Card>();
ArrayList<Card> player4 = new ArrayList<Card>();

ArrayList<Card> deck = Card.newDeck();
Random random = new Random();
int j = 1;
for (int i = 0; i < 52; i++) {
int temp = random.nextInt(52);
if (j == 1) {
player1.add(deck.get(i));
j++;
continue;
} else if (j == 2) {
player2.add(deck.get(i));
j++;
continue;
} else if (j == 3) {
player3.add(deck.get(i));

j++;
continue;
} else if (j == 4) {
player4.add(deck.get(i));
j = 1;
continue;
}
}
System.out.println(" Player 1 " + player1);
System.out.println(" Player 2 " + player2);
System.out.println(" Player 3 " + player3);
System.out.println(" Player 4 " + player4);
}
}

Comments

Popular posts from this blog

I get wrong characters when retreiving the message body of an email using TIdIMAP4.UIDRetrieveTextPeek2()

How to drop the all the 1's in a correlation matrix

Today Walkin 14th-Sept