25 Topics
Chapter•270 Minutes

Java Progressive DSA Master Bank (25 Core Algorithmic Questions)

25 essential Java Data Structures & Algorithms interview questions complete with step-by-step logic, code implementations, asymptotic complexities, and interactive quizzes.

Q1: How do you count the number of set bits (1s) in an integer using Brian Kernighan's Algorithm?

Brian Kernighan's Algorithm repeatedly clears the lowest set bit of an integer n using the bitwise operation n = n & (n - 1). Each iteration flips the rightmost set bit to 0, running in $O(k)$ time where $k$ is the number of set bits.

Brian Kernighan's Bit Counting
public class BitCount {
    public static int countSetBits(int n) {
        int count = 0;
        while (n != 0) {
            n = n & (n - 1); // Clears rightmost set bit
            count++;
        }
        return count;
    }
}

Flips the lowest set bit in each iteration until the number becomes zero.

Key Takeaways
  • n & (n - 1) clears the rightmost set bit in $O(1)$ time.

  • Total iterations equal the count of set bits rather than total bits ($32$ or $64$).

Knowledge Check

What is the result of applying n & (n - 1) to n = 12 (binary 1100)?

Q2: How do you check if an integer is a Power of Two in O(1) time?

A positive integer is a power of two if it has exactly one set bit in its binary representation. Evaluating (n > 0) && ((n & (n - 1)) == 0) checks this property in constant time.

Power of Two Check
public class PowerOfTwo {
    public static boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}

Returns true strictly for positive integers containing a single 1 bit.

Key Takeaways
  • Powers of 2 have exactly one bit set to 1 in binary.

  • (n & (n - 1)) == 0 clears that single set bit, resulting in 0.

Knowledge Check

Why is the condition n > 0 mandatory in the expression n > 0 && (n & (n - 1)) == 0?

Q3: Given an array where every element appears twice except one, how do you find the single number in O(n) time and O(1) space?

Use the properties of the bitwise XOR operator ($oplus$):

  1. $x oplus x = 0$ (Self-inverse)
  2. $x oplus 0 = x$ (Identity)
  3. $x oplus y = y oplus x$ (Commutative) XORing all elements across the array cancels out all paired numbers, leaving the single unique number.
Single Number XOR Solution
public class SingleNumber {
    public static int findSingle(int[] nums) {
        int result = 0;
        for (int num : nums) {
            result ^= num;
        }
        return result;
    }
}

Accumulates XOR results across the array to isolate the un-paired value.

Key Takeaways
  • XORing paired duplicate values reduces them to 0.

  • Executes in $O(n)$ time with $O(1)$ auxiliary space.

Knowledge Check

What is the result of evaluating 5 ^ 3 ^ 5?

Q4: How do you rotate an N x N 2D matrix 90 degrees clockwise in-place?

Rotating a matrix 90 degrees clockwise in-place involves two steps:

  1. Transpose the matrix: Swap matrix[i][j] with matrix[j][i] for all $i < j$.
  2. Reverse each row: Swap elements from outer columns inward (matrix[i][left] with matrix[i][right]).
Matrix 90 Degree Rotation
public class RotateMatrix {
    public static void rotate(int[][] matrix) {
        int n = matrix.length;
        // Step 1: Transpose
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        // Step 2: Reverse rows
        for (int i = 0; i < n; i++) {
            int left = 0, right = n - 1;
            while (left < right) {
                int temp = matrix[i][left];
                matrix[i][left] = matrix[i][right];
                matrix[i][right] = temp;
                left++; right--;
            }
        }
    }
}

Transposes the grid matrix across its main diagonal and flips rows horizontally.

Key Takeaways
  • Step 1: Transpose matrix along the main diagonal.

  • Step 2: Reverse elements horizontally in each row.

Knowledge Check

How would you rotate an N x N matrix 90 degrees COUNTER-clockwise in-place?

Q5: How do you traverse an M x N 2D matrix in Spiral Order?

Maintain four boundary boundaries: top, bottom, left, and right. Traverse right along top, down along right, left along bottom (if top <= bottom), and up along left (if left <= right), shrinking boundaries inward after each direction traversal.

Spiral Matrix Traversal
import java.util.*;

public class SpiralMatrix {
    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0) return result;
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;
        while (top <= bottom && left <= right) {
            for (int col = left; col <= right; col++) result.add(matrix[top][col]);
            top++;
            for (int row = top; row <= bottom; row++) result.add(matrix[row][right]);
            right--;
            if (top <= bottom) {
                for (int col = right; col >= left; col--) result.add(matrix[bottom][col]);
                bottom--;
            }
            if (left <= right) {
                for (int row = bottom; row >= top; row--) result.add(matrix[row][left]);
                left++;
            }
        }
        return result;
    }
}

Scans grid perimeters clockwise while shrinking boundary limits.

Key Takeaways
  • Track four dynamic boundary boundaries.

  • Shrink boundaries inward and verify non-overlapping conditions before scanning reverse directions.

Knowledge Check

Why are the checks top <= bottom and left <= right required inside the spiral loop before processing bottom and left sweeps?

Q6: How do you implement a Queue using two Stacks (and analyze amortized time complexity)?

Maintain two stacks: inputStack and outputStack.

  • enqueue(x): Push x onto inputStack ($O(1)$).
  • dequeue(): If outputStack is empty, pop all elements from inputStack and push them onto outputStack (reversing their order). Pop top of outputStack ($O(1)$ amortized).
Queue Using Stacks Implementation
import java.util.ArrayDeque;
import java.util.Deque;

public class MyQueue {
    private final Deque<Integer> input = new ArrayDeque<>();
    private final Deque<Integer> output = new ArrayDeque<>();

    public void push(int x) {
        input.push(x);
    }
    public int pop() {
        peek();
        return output.pop();
    }
    public int peek() {
        if (output.isEmpty()) {
            while (!input.isEmpty()) {
                output.push(input.pop());
            }
        }
        return output.peek();
    }
    public boolean empty() {
        return input.isEmpty() && output.isEmpty();
    }
}

Transfers items from input to output stack on demand to establish FIFO queue order.

Key Takeaways
  • inputStack accepts fresh incoming items.

  • outputStack provides FIFO ordering with amortized $O(1)$ operations.

Knowledge Check

What is the amortized time complexity of the pop() method in a queue built using two stacks?

Q7: How do you design a Min Stack that retrieves the minimum element in O(1) time?

Maintain an auxiliary stack (minStack) alongside the primary stack. When pushing value x, push Math.min(x, minStack.peek()) onto minStack. When popping from the primary stack, pop from minStack simultaneously.

Min Stack Implementation
import java.util.ArrayDeque;
import java.util.Deque;

public class MinStack {
    private final Deque<Integer> stack = new ArrayDeque<>();
    private final Deque<Integer> minStack = new ArrayDeque<>();

    public void push(int val) {
        stack.push(val);
        int currentMin = minStack.isEmpty() ? val : Math.min(val, minStack.peek());
        minStack.push(currentMin);
    }
    public void pop() {
        stack.pop();
        minStack.pop();
    }
    public int top() {
        return stack.peek();
    }
    public int getMin() {
        return minStack.peek();
    }
}

Keeps stack min state in sync across every push and pop operation.

Key Takeaways
  • Auxiliary minStack tracks the current minimum value at every stack depth.

  • All operations (push, pop, top, getMin) run in $O(1)$ time.

Knowledge Check

What is the auxiliary space complexity of the Min Stack implementation?

Q8: How do you search for a target value in a Rotated Sorted Array in O(log n) time?

Use Modified Binary Search. In a rotated sorted array, at least one half (left to mid OR mid to right) is guaranteed to be strictly sorted. Determine which half is sorted, check if target lies within its bounds, and adjust binary search boundaries left / right accordingly.

Rotated Sorted Array Search
public class RotatedSearch {
    public static int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) return mid;
            if (nums[left] <= nums[mid]) { // Left half sorted
                if (nums[left] <= target && target < nums[mid]) right = mid - 1;
                else left = mid + 1;
            } else { // Right half sorted
                if (nums[mid] < target && target <= nums[right]) left = mid + 1;
                else right = mid - 1;
            }
        }
        return -1;
    }
}

Determines the sorted sub-array half to locate target boundaries in logarithmic time.

Key Takeaways
  • Identify the sorted half in each binary search step.

  • Narrows search range in $O(log n)$ time.

Knowledge Check

How do you calculate mid safely in Java binary search to prevent integer overflow?

Q9: How do you find the K Closest Points to the Origin (0,0)?

Calculate distance squared $x^2 + y^2$. Use a Max-Heap (PriorityQueue) of size $k$ ordered by Euclidean distance descending. Push points into the heap; if heap size exceeds $k$, pop the maximum distance point. Returns $k$ closest points in $O(n log k)$ time.

K Closest Points Max-Heap Solution
import java.util.PriorityQueue;

public class KClosestPoints {
    public static int[][] kClosest(int[][] points, int k) {
        PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
            (a, b) -> Integer.compare((b[0]*b[0] + b[1]*b[1]), (a[0]*a[0] + a[1]*a[1]))
        );
        for (int[] p : points) {
            maxHeap.offer(p);
            if (maxHeap.size() > k) {
                maxHeap.poll();
            }
        }
        int[][] result = new int[k][2];
        for (int i = 0; i < k; i++) {
            result[i] = maxHeap.poll();
        }
        return result;
    }
}

Maintains $k$ smallest Euclidean distance points inside a bounded Max-Heap.

Key Takeaways
  • Avoid Math.sqrt() by comparing squared distances ($x^2 + y^2$).

  • Use size-bounded Max-Heap ($O(n log k)$ runtime).

Knowledge Check

Why is comparing (x1^2 + y1^2) directly preferred over using Math.sqrt(x1^2 + y1^2)?

Q10: How do you validate whether a Binary Tree is a valid Binary Search Tree (BST)?

Pass dynamic valid range constraints (min and max pointers) recursively down the tree. For a node to be valid, its value must satisfy min < node.val < max. When recurring left, update max = node.val. When recurring right, update min = node.val.

Validate BST Solution
public class ValidateBST {
    public static boolean isValidBST(TreeNode root) {
        return validate(root, null, null);
    }
    private static boolean validate(TreeNode node, Integer low, Integer high) {
        if (node == null) return true;
        if ((low != null && node.val <= low) || (high != null && node.val >= high)) {
            return false;
        }
        return validate(node.left, low, node.val) && validate(node.right, node.val, high);
    }
}

Validates that node values fall within strict minimum and maximum subtree constraints.

Key Takeaways
  • Use Long pointers or object wrappers for min/max bounds to handle Integer.MIN_VALUE edge cases.

  • Validates that every left descendant is strictly smaller and right descendant is strictly larger.

Knowledge Check

Why is simply checking node.left.val < node.val && node.right.val > node.val for each node insufficient to validate a BST?

Q11: How do you Invert a Binary Tree (flip left and right child pointers)?

Recursively swap the left and right child pointers of every node in the binary tree. Base case: if root == null, return null. Store root.left in a temporary variable, assign root.left = invertTree(root.right), and root.right = invertTree(temp). Return root.

Invert Binary Tree Solution
public class InvertBinaryTree {
    public static TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        TreeNode temp = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(temp);
        return root;
    }
}

Swaps left and right children recursively across the tree.

Key Takeaways
  • Recursive post-order / pre-order traversal pointer swapping.

  • Time Complexity: $O(n)$, visiting every tree node once.

Knowledge Check

What is the maximum recursion stack depth when inverting a completely skewed degenerate tree with N nodes?

Q12: How do you compute the Diameter of a Binary Tree?

The diameter is the length of the longest path between any two nodes in a tree (which may or may not pass through root). Compute the height of left and right subtrees recursively: at each node, currentDiameter = leftHeight + rightHeight. Maintain a global max variable.

Binary Tree Diameter Solution
public class TreeDiameter {
    private static int maxDiameter = 0;
    public static int diameterOfBinaryTree(TreeNode root) {
        maxDiameter = 0;
        getHeight(root);
        return maxDiameter;
    }
    private static int getHeight(TreeNode node) {
        if (node == null) return 0;
        int left = getHeight(node.left);
        int right = getHeight(node.right);
        maxDiameter = Math.max(maxDiameter, left + right);
        return 1 + Math.max(left, right);
    }
}

Updates global maximum path length while calculating subtree heights recursively.

Key Takeaways
  • Diameter at any node = leftHeight + rightHeight.

  • Returns tree height to parent callers while tracking maximum diameter globally.

Knowledge Check

Does the longest diameter path in a binary tree ALWAYS pass through the root node?

Q13: How do you reconstruct a Binary Tree from Preorder and Inorder traversal arrays?

Preorder traversal determines the root node (first element). Inorder traversal splits the tree into left and right subtrees relative to the root node position. Map inorder values to indices using a HashMap<Integer, Integer> for $O(1)$ lookup, and construct the tree recursively.

Tree Construction from Preorder & Inorder
import java.util.HashMap;
import java.util.Map;

public class BuildTree {
    private static int preIndex = 0;
    private static final Map<Integer, Integer> inMap = new HashMap<>();

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        preIndex = 0;
        inMap.clear();
        for (int i = 0; i < inorder.length; i++) inMap.put(inorder[i], i);
        return helper(preorder, 0, inorder.length - 1);
    }
    private static TreeNode helper(int[] preorder, int left, int right) {
        if (left > right) return null;
        int rootVal = preorder[preIndex++];
        TreeNode root = new TreeNode(rootVal);
        int inIndex = inMap.get(rootVal);
        root.left = helper(preorder, left, inIndex - 1);
        root.right = helper(preorder, inIndex + 1, right);
        return root;
    }
}

Identifies root nodes using preorder indexing and partitions subtrees using inorder index bounds.

Key Takeaways
  • Preorder gives root values sequentially.

  • Inorder index map determines left/right subtree element boundaries.

Knowledge Check

Why is an index lookup HashMap constructed for the inorder array elements?

Q14: How do you Clone a Undirected Graph (Deep Copy with Cycles)?

Use a HashMap<Node, Node> to store mappings of (originalNode -> clonedNode) to handle cyclic references. Traverse graph using DFS or BFS: for each node, if not already cloned, create a new clone node, place in map, and recursively clone neighbor relationships.

DFS Graph Clone Solution
import java.util.*;

class Node {
    public int val;
    public List<Node> neighbors;
    public Node(int _val) { val = _val; neighbors = new ArrayList<>(); }
}

public class CloneGraph {
    private static final Map<Node, Node> visited = new HashMap<>();
    public static Node cloneGraph(Node node) {
        if (node == null) return null;
        if (visited.containsKey(node)) return visited.get(node);
        Node cloneNode = new Node(node.val);
        visited.put(node, cloneNode);
        for (Node neighbor : node.neighbors) {
            cloneNode.neighbors.add(cloneGraph(neighbor));
        }
        return cloneNode;
    }
}

Tracks visited nodes in a map to manage cyclic graph references during deep cloning.

Key Takeaways
  • HashMap tracks cloned copies to prevent infinite recursion on graph cycles.

  • DFS/BFS graph traversal produces identical deep-copied connectivity.

Knowledge Check

What issue arises if you attempt to deep copy a cyclic graph without maintaining a visited map?

Q15: How do you implement Dijkstra's Algorithm for Shortest Paths in Weighted Graphs?

Dijkstra's Algorithm computes shortest paths from a single source node in weighted graphs with non-negative edge weights. Initialize dist[] array filled with $infty$, with dist[src] = 0. Use a PriorityQueue storing (node, distance). Poll node with minimum distance; relax neighbors if dist[u] + weight < dist[v].

Dijkstra's Shortest Path Algorithm
import java.util.*;

public class Dijkstra {
    public static int[] shortestPath(int n, List<List<int[]>> adj, int src) {
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[src] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
        pq.offer(new int[]{src, 0});
        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int u = curr[0], d = curr[1];
            if (d > dist[u]) continue;
            for (int[] edge : adj.get(u)) {
                int v = edge[0], weight = edge[1];
                if (dist[u] + weight < dist[v]) {
                    dist[v] = dist[u] + weight;
                    pq.offer(new int[]{v, dist[v]});
                }
            }
        }
        return dist;
    }
}

Relaxes graph edge weights using a Min-PriorityQueue.

Key Takeaways
  • Min-PriorityQueue processes closest unvisited nodes greedy style.

  • Time Complexity: $O((V + E) log V)$ using Min-Heap.

Knowledge Check

Why does standard Dijkstra's Algorithm fail or enter infinite loops on graphs containing NEGATIVE edge weights?

Q16: How do you solve Climbing Stairs using Dynamic Programming and Space Optimization?

You are climbing a staircase of $n$ steps. You can climb 1 or 2 steps at a time. Recurrence relation: $dp[i] = dp[i-1] + dp[i-2]$ (Fibonacci pattern). Optimize space to $O(1)$ using two variables (prev1, prev2).

Climbing Stairs Space-Optimized Solution
public class ClimbStairs {
    public static int climbStairs(int n) {
        if (n <= 2) return n;
        int prev2 = 1, prev1 = 2;
        for (int i = 3; i <= n; i++) {
            int current = prev1 + prev2;
            prev2 = prev1;
            prev1 = current;
        }
        return prev1;
    }
}

Computes step combinations iteratively using constant auxiliary space.

Key Takeaways
  • Base cases: $dp[1] = 1$, $dp[2] = 2$.

  • Space optimized to $O(1)$ variable swaps.

Knowledge Check

What is the time and space complexity of the space-optimized Climbing Stairs algorithm?

Q17: How do you solve the House Robber problem using Dynamic Programming?

Robbing adjacent houses triggers security alarms. At each house $i$, choose maximum of:

  1. Rob house $i$: nums[i] + rob(i - 2)
  2. Skip house $i$: rob(i - 1) Recurrence: $dp[i] = max(nums[i] + dp[i-2], dp[i-1])$.
House Robber DP Solution
public class HouseRobber {
    public static int rob(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int prev2 = 0, prev1 = 0;
        for (int num : nums) {
            int temp = Math.max(num + prev2, prev1);
            prev2 = prev1;
            prev1 = temp;
        }
        return prev1;
    }
}

Tracks optimal loot values while skipping adjacent houses.

Key Takeaways
  • Recurrence relation: $dp[i] = max(nums[i] + dp[i-2], dp[i-1])$.

  • Optimize memory to $O(1)$ space using two variables.

Knowledge Check

If houses are arranged in a CIRCLE (House Robber II), how do you adapt the solution?

Q18: How do you solve the 0/1 Knapsack Problem using Dynamic Programming?

Given $n$ items with weights $w[i]$ and values $v[i]$, maximize total value in knapsack capacity $W$. State $dp[i][w]$ represents maximum value using first $i$ items with capacity $w$. Recurrence: if $w[i-1] le w$, $dp[i][w] = max(v[i-1] + dp[i-1][w - w[i-1]], dp[i-1][w])$.

0/1 Knapsack 1D Array Optimization
public class Knapsack {
    public static int knapsack(int W, int[] wt, int[] val, int n) {
        int[] dp = new int[W + 1];
        for (int i = 0; i < n; i++) {
            for (int w = W; w >= wt[i]; w--) { // Reverse iteration
                dp[w] = Math.max(dp[w], val[i] + dp[w - wt[i]]);
            }
        }
        return dp[W];
    }
}

Iterates backwards over capacity $W$ to update knapsack state in 1D array space.

Key Takeaways
  • 2D DP table size: $(N+1) imes (W+1)$.

  • Can be optimized to a 1D DP array of size $W+1$ by traversing backwards.

Knowledge Check

Why MUST the inner loop iterate BACKWARDS from W down to wt[i] in the 1D array DP space optimization?

Q19: How do you solve Word Search on a 2D Board using Recursion / Backtracking?

Iterate through matrix cells. When starting character matches, invoke DFS backtracking (backtrack(board, word, r, c, index)). Mark current cell as visited (e.g. board[r][c] = '#'), recursively explore 4-directional neighbors, and restore cell state (board[r][c] = temp) during back-step.

Word Search Backtracking Solution
public class WordSearch {
    public static boolean exist(char[][] board, String word) {
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[0].length; c++) {
                if (dfs(board, word, r, c, 0)) return true;
            }
        }
        return false;
    }
    private static boolean dfs(char[][] board, String word, int r, int c, int i) {
        if (i == word.length()) return true;
        if (r < 0 || c < 0 || r >= board.length || c >= board[0].length || board[r][c] != word.charAt(i)) {
            return false;
        }
        char temp = board[r][c];
        board[r][c] = '#'; // Mark visited
        boolean found = dfs(board, word, r + 1, c, i + 1) ||
                        dfs(board, word, r - 1, c, i + 1) ||
                        dfs(board, word, r, c + 1, i + 1) ||
                        dfs(board, word, r, c - 1, i + 1);
        board[r][c] = temp; // Backtrack restore
        return found;
    }
}

Marks board cells temporarily during DFS search and restores state during backtracking steps.

Key Takeaways
  • DFS recursive grid traversal with backtracking.

  • Restoring visited state during back-stepping allows alternative paths to reuse board cells.

Knowledge Check

What is the purpose of board[r][c] = temp during the backtracking step?

Q20: How do you generate all Subsets (Power Set) of a set of unique integers using Backtracking?

Use Backtracking to build decision trees. At each recursive index step, append current tempList state to result. Loop from start index to end of array: append nums[i] to tempList, recurse backtrack(i + 1), and remove last element (tempList.remove(tempList.size() - 1)) to backtrack.

Subsets Backtracking Solution
import java.util.*;

public class Subsets {
    public static List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<>(), nums, 0);
        return result;
    }
    private static void backtrack(List<List<Integer>> result, List<Integer> temp, int[] nums, int start) {
        result.add(new ArrayList<>(temp));
        for (int i = start; i < nums.length; i++) {
            temp.add(nums[i]);
            backtrack(result, temp, nums, i + 1);
            temp.remove(temp.size() - 1); // Backtrack
        }
    }
}

Appends subset states to result and backtracks choices step-by-step.

Key Takeaways
  • Generates $2^n$ unique subset combinations.

  • Backtracking template: Add element -> Recurse -> Remove element.

Knowledge Check

How many total subsets are generated for an input set containing N distinct elements?

Q21: How do you solve Combination Sum (reusing numbers to hit target sum)?

Find all unique combinations of candidates that sum to target. candidates can be chosen unlimited times. Recursively subtract candidate from target. If target == 0, add snapshot to result. If target < 0, return. Pass i (not i + 1) to recursive call to allow element reuse.

Combination Sum Backtracking
import java.util.*;

public class CombinationSum {
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<>(), candidates, target, 0);
        return result;
    }
    private static void backtrack(List<List<Integer>> result, List<Integer> temp, int[] candidates, int remain, int start) {
        if (remain < 0) return;
        if (remain == 0) { result.add(new ArrayList<>(temp)); return; }
        for (int i = start; i < candidates.length; i++) {
            temp.add(candidates[i]);
            backtrack(result, temp, candidates, remain - candidates[i], i); // i permits reuse
            temp.remove(temp.size() - 1);
        }
    }
}

Reuses current candidate elements by passing index i recursively.

Key Takeaways
  • Allowing element reuse requires calling backtrack(i) instead of i + 1.

  • Prune recursion branches when target becomes negative.

Knowledge Check

What parameter controls whether candidate elements can be reused multiple times during backtracking?

Q22: How do you implement a Trie (Prefix Tree) for efficient word insertion and prefix searching?

A Trie is a tree data structure used for fast string prefix lookups. Each node contains a TrieNode[26] child array and a boolean isEndOfWord flag. Operations insert(word), search(word), and startsWith(prefix) run in $O(L)$ time where $L$ is word length.

Trie (Prefix Tree) Implementation
public class Trie {
    static class TrieNode {
        TrieNode[] children = new TrieNode[26];
        boolean isEnd = false;
    }
    private final TrieNode root = new TrieNode();

    public void insert(String word) {
        TrieNode curr = root;
        for (char c : word.toCharArray()) {
            int idx = c - 'a';
            if (curr.children[idx] == null) curr.children[idx] = new TrieNode();
            curr = curr.children[idx];
        }
        curr.isEnd = true;
    }
    public boolean search(String word) {
        TrieNode node = getNode(word);
        return node != null && node.isEnd;
    }
    public boolean startsWith(String prefix) {
        return getNode(prefix) != null;
    }
    private TrieNode getNode(String str) {
        TrieNode curr = root;
        for (char c : str.toCharArray()) {
            int idx = c - 'a';
            if (curr.children[idx] == null) return null;
            curr = curr.children[idx];
        }
        return curr;
    }
}

Builds prefix paths inside node arrays for $O(L)$ prefix lookups.

Key Takeaways
  • $O(L)$ insertion and lookup time complexity.

  • Saves storage by sharing common prefix branch pathways across words.

Knowledge Check

What is the time complexity of searching if a prefix exists in a Trie containing N words of average length L?

Q23: How do you implement Disjoint Set Union (DSU / Union-Find) with Path Compression and Union by Rank?

DSU manages partitioned disjoint sets across elements. Operations:

  1. find(x): Returns root representative of x. Uses Path Compression (parent[x] = find(parent[x])) to flatten tree paths.
  2. union(x, y): Connects sets containing x and y. Uses Union by Rank to attach smaller trees beneath taller tree roots. Amortized operational time: $O(alpha(n))$ (Nearly constant Inverse Ackermann function).
Union-Find with Path Compression & Rank
public class UnionFind {
    private final int[] parent;
    private final int[] rank;

    public UnionFind(int size) {
        parent = new int[size];
        rank = new int[size];
        for (int i = 0; i < size; i++) parent[i] = i;
    }
    public int find(int i) {
        if (parent[i] == i) return i;
        return parent[i] = find(parent[i]); // Path compression
    }
    public boolean union(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX != rootY) {
            if (rank[rootX] < rank[rootY]) parent[rootX] = rootY;
            else if (rank[rootX] > rank[rootY]) parent[rootY] = rootX;
            else { parent[rootY] = rootX; rank[rootX]++; }
            return true;
        }
        return false; // Already in same set
    }
}

Flattens set trees dynamically to execute union and find queries in near constant time.

Key Takeaways
  • Path Compression flattens parent pointers during find().

  • Union by Rank maintains balanced tree depth.

  • Amortized operational time complexity: $O(alpha(n))$.

Knowledge Check

What is the amortized time complexity per operation in a DSU implementation utilizing both Path Compression and Union by Rank?

Q24: How do you find the Top K Frequent Elements in O(n) time using Bucket Sort?

  1. Build a character/number frequency map (map.put(num, count)).
  2. Create an array of lists List<Integer>[] buckets = new List[nums.length + 1], where array index represents element frequency.
  3. Populate buckets with numbers corresponding to their frequency count.
  4. Iterate buckets backwards from nums.length down to 1, collecting elements until $k$ elements are gathered.
Bucket Sort Top K Frequent Elements
import java.util.*;

public class TopKFrequent {
    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int num : nums) countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        List<Integer>[] bucket = new List[nums.length + 1];
        for (int key : countMap.keySet()) {
            int freq = countMap.get(key);
            if (bucket[freq] == null) bucket[freq] = new ArrayList<>();
            bucket[freq].add(key);
        }
        int[] result = new int[k];
        int index = 0;
        for (int pos = bucket.length - 1; pos >= 0 && index < k; pos--) {
            if (bucket[pos] != null) {
                for (int num : bucket[pos]) {
                    result[index++] = num;
                    if (index == k) return result;
                }
            }
        }
        return result;
    }
}

Uses array indices to group elements by occurrence frequency for linear $O(n)$ performance.

Key Takeaways
  • Bucket index represents element frequency count.

  • Achieves optimal $O(n)$ linear time complexity, bypassing $O(n log n)$ sorting.

Knowledge Check

Why is Bucket Sort able to solve Top K Frequent Elements in O(N) time compared to Min-Heap's O(N log K)?

Q25: How do you solve the Trapping Rain Water problem in O(n) time and O(1) space?

Use Two Pointers (left = 0, right = len - 1) maintaining leftMax and rightMax. At each step, if height[left] < height[right]:

  • If height[left] >= leftMax, update leftMax = height[left].
  • Else, add leftMax - height[left] to total water.
  • Increment left. Else, process right pointer symmetrically.
Trapping Rain Water Two-Pointer Solution
public class TrappingRainWater {
    public static int trap(int[] height) {
        if (height == null || height.length == 0) return 0;
        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        int totalWater = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] >= leftMax) leftMax = height[left];
                else totalWater += leftMax - height[left];
                left++;
            } else {
                if (height[right] >= rightMax) rightMax = height[right];
                else totalWater += rightMax - height[right];
                right--;
            }
        }
        return totalWater;
    }
}

Calculates trapped water at boundary limits while moving inward.

Key Takeaways
  • Water trapped at index $i$ depends on $min( ext{leftMax}, ext{rightMax}) - ext{height}[i]$.

  • Two pointers process lower boundary limits inward in $O(n)$ time and $O(1)$ space.

Knowledge Check

What determines the trapped water height at any index i?