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

//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.peek() //apple
queue.remove();queue.remove();queue.poll(); //apple,cherry,banana

//Iterating queue
Iterator it = queue.iterator();

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

1.3 Stack

        Stack<Integer> a = new Stack<>();
        while (!a.isEmpty()) {

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()) {

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


2.6: Important Math functions

Math.abs(-10); //10

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
//initial and append to string builder
StringBuilder sb = new StringBuilder();

3: Sorting Strategies

3.1 : Sort Array in Java

We can use Arrays.sort method

int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
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; = name;
        this.age = age;
    public int compareTo(Player otherPlayer) {
        return, getRanking());

3.3: Comparator Interface

public class Player{

    private int ranking;
    private String name;
    private int age;
public class PlayerRankingComparator implements Comparator<Player> {
    public int compare(Player firstPlayer, Player secondPlayer) {
        return, 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) ->, order2.getId()));
        Collections.sort(allOrder, (order1, order2) -> order1.getName().compareTo(order2.getName()));


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());

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



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);
        Queue<Map.Entry<String, Integer>> queue = new PriorityQueue<>((h1, h2) ->, h2.getValue()));
        for(Map.Entry<String, Integer> entry : map.entrySet()){

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) ->, 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");



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";


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<>();
        int level = 0;
            levels.add(new ArrayList<>());
            int levelSize = q.size();
            for(int i=0 ;i < levelSize ;i++) {
                TreeNode node = q.remove();
                if (node.left != null) q.add(node.left);
                if (node.right != null) q.add(node.right);
        return levels;