Interview Cheat Sheet

My primary language at work is javascript. But I prefer solving interview questions in java. I tend to forget the essentials of Java. So I am storing important topics of java here which will be used in interviews.

1 : Data structures

1.1: Overview

The below table shows various differences between the Collection classes. The terms used
in the table are -

1) AD - Allow Duplicates:

2) AN - Allow Null

Time Complexities

1.2: Queue

//queue 
//add -> queue.add(e) || queue.offer(e)
//remove -> 
    //queue.remove() -> returns head
    //queue.poll() -> returns head | return null if no element
//read first element -> queue.peek()
Queue<String> queue = new LinkedList<>();
// add elements to the queue
queue.add("apple");
queue.add("cherry");
queue.offer("banana");
queue.peek() //apple
queue.remove();queue.remove();queue.poll(); //apple,cherry,banana

//Iterating queue
Iterator it = queue.iterator();
while(it.hasNext()){
    System.out.println(itr.next());  
}


//priorityqueue maintains order
Queue<String> queue = new PriorityQueue<>();
queue.add("apple");
queue.add("banana");
queue.add("cherry");
queue.remove();queue.remove();queue.remove(); //apple,banana,cherry

1.3 Stack

        Stack<Integer> a = new Stack<>();
        a.push(10);
        a.push(9);
        a.push(8);
        a.push(2);
        while (!a.isEmpty()) {
            System.out.println(a.pop());
        }

2: Conversions & Iterations & Imp functions

2.1: Array to HashMap

Map<Integer, Integer> map = new HashMap<>();

for(int i=0 ;i<nums.length;i++) {     
   map.put(nums[i] , map.getOrDefault(nums[i], 0) +1);
}

2.2: String:: character frequency to array

String word;
int charArray[] = new int[26];
for(char c : word.toCharArray()) {
     charArray[c-'a']++;
}

2.3: Get all values & keys of hashmap to list

Map<Integer, Integer> map = new HashMap<>();
List<Integer> values = new ArrayList<>(map.values());
List<Integer> keys = new ArrayList<>(map.keySet());

2.4: How to Iterate HashMap?

Each element of map is of type Map.Entry<Integer, Integer>

map.entrySet() will return list of elements whos type is Map.Entry<Integer, Integer>

//Each element of 
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {

            int value=entry.getValue();
            int key = entry.getKey();
}

2.5: Max and Min Integers

Integer.MAX_VALUE
Integer.MIN_VALUE

2.6: Important Math functions

Math.abs(-10); //10
Math.abs(-10.7);//10.7

2.7: length vs length() in Java

array.length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array.

string.length() : length() method is a final method which is applicable for string objects. The length() method returns the number of characters present in the string.

2.8: String || Array functions

//char array to string
new String(charArray);
//print array in one line
System.out.println(Arrays.toString(array));
//initial and append to string builder
StringBuilder sb = new StringBuilder();
sb.append();

3: Sorting Strategies

3.1 : Sort Array in Java

We can use Arrays.sort method

int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
  System.out.print(num + " ");
}

3.2: Comparable Interface

public class Player implements Comparable<Player>{

    private int ranking;
    private String name;
    private int age;

    public Player(int ranking, String name, int age) {
        this.ranking = ranking;
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Player otherPlayer) {
        return Integer.compare(otherPlayer.getRanking(), getRanking());
    }
}

3.3: Comparator Interface

public class Player{

    private int ranking;
    private String name;
    private int age;
}
public class PlayerRankingComparator implements Comparator<Player> {
    @Override
    public int compare(Player firstPlayer, Player secondPlayer) {
        return Integer.compare(firstPlayer.getRanking(), secondPlayer.getRanking());
    }
}

public static void main(String[] args) {
   List<Player> allPlayers = new ArrayList<>();
   Collections.sort(allPlayers, PlayerRankingComparator);
}

3.4: Comparator using java 8

public class Order {
    int id;
    String name;
}

public class Runner {
    public static void main(String[] args) {
        Order[] orders = new Order[]{
                new Order(10, "bat"),
                new Order(5, "apples"),
                new Order(12, "mat"),
                new Order(7, "cat"),
                new Order(12, "mat"),
                new Order(4, "elephant")
        };
        List<Order> allOrder = Arrays.asList(orders);
        Collections.sort(allOrder, (order1, order2) -> Integer.compare(order1.getId(), order2.getId()));
        System.out.println(allOrder);
        Collections.sort(allOrder, (order1, order2) -> order1.getName().compareTo(order2.getName()));
        System.out.println(allOrder);

    }
}

3.4: Sort HashMap based on values (convert to list)

  • Add Entry set of HashMap to Arrayslist

  • write a comparator based on entry values

public class SortStringCharFrequency {

    public static void main(String[] args) {

        String str = "applesisalsoandapple";
        char[] arr = str.toCharArray();

        Map<Character, Integer> map = new HashMap();

        for(Character ch : arr) {
            map.put(ch, map.getOrDefault(ch, 0)+1);
        }

        List<Map.Entry<Character, Integer> > sortedDict = new ArrayList<>(map.entrySet());

        System.out.println(sortedDict);
        //Ascending order
        Collections.sort(sortedDict, (o1, o2) -> o1.getValue() == o2.getValue() ? o1.getKey()-o2.getKey() : Integer.compare(o1.getValue(),o2.getValue()));

        System.out.println(sortedDict);

    }
}

3.5: Sort HashMap based on values (convert to Priority Queue)

public class HashMapRunner {
    public static void main(String[] args){
        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("bat", 2);
        map.put("apple", 200);
        map.put("cat", 100);
        map.put("dog", 4);
        map.put("elephant", 5);
        System.out.println(map);
        Queue<Map.Entry<String, Integer>> queue = new PriorityQueue<>((h1, h2) -> Integer.compare(h1.getValue(), h2.getValue()));
        for(Map.Entry<String, Integer> entry : map.entrySet()){
            queue.add(entry);
        }
        System.out.println(queue);
    }
}

3.6: PriorityQueue with Custom Compartor

public class Player{
    private int ranking;
    private String name;
    private int age;
}

public static void main(String[] args) {
  Comparator<Player> ageComparator = (Player p1, Player p2) -> Integer.compare(p1.getAge(), p2.getAge());
  Queue<Player> q = new PriorityQueue(ageComparator);
  q.add(new Player(1,"shyam", 30));
  q.add(new Player(10,"chinnu", 27));
  q.add(new Player(5,"chintu", 25));
  System.out.println(q); //{5,"chintu", 25},{10,"chinnu", 27},{1,"shyam", 30}
}

3.7: No of comparisons for sorting algo

For any comparison-based sorting algorithm, the minimum number of comparisons required to sort an array of n elements is O(n log n).

String Comparison

“==” only checks the referential equality of two Strings*,* meaning if they reference the same object or not.

String string1 = "using comparison operator";
String string2 = "using comparison operator";
String string3 = new String("using comparison operator");

assertThat(string1 == string2).isTrue(); //true
assertThat(string1 == string3).isFalse(); //false

The String class overrides the equals() inherited from Object. This method compares two Strings character by character, ignoring their address.

It considers them equal if they are of the same length and the characters are in same order:

String string1 = "using equals method";
String string2 = "using equals method";

String string3 = "using EQUALS method";
String string4 = new String("using equals method");

assertThat(string1.equals(string2)).isTrue();
assertThat(string1.equals(string4)).isTrue();

assertThat(string1.equals(null)).isFalse();
assertThat(string1.equals(string3)).isFalse();

The compareTo() method returns an int type value and compares two Strings character by character lexicographically based on a dictionary or natural ordering.

This method returns 0 if two Strings are equal*,* a negative number if the first String comes before the argument, and a number greater than zero if the first String comes after the argument String.

String author = "author";
String book = "book";
String duplicateBook = "book";

assertThat(author.compareTo(book))
  .isEqualTo(-1);
assertThat(book.compareTo(author))
  .isEqualTo(1);
assertThat(duplicateBook.compareTo(book))
  .isEqualTo(0);

Generate Level Order traversal


List<List<Integer> levelOrderTraversal(Node root) {
    List<List<Integer>> levels = new ArrayList<>();
        if (root == null) {
            return levels;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int level = 0;
        while(!q.isEmpty()){
            levels.add(new ArrayList<>());
            System.out.println(levels);
            int levelSize = q.size();
            for(int i=0 ;i < levelSize ;i++) {
                TreeNode node = q.remove();
                levels.get(level).add(node.data);
                if (node.left != null) q.add(node.left);
                if (node.right != null) q.add(node.right);
            }
            level++;
        }
        return levels;
}