FAANG DSA • Java 21 • 28+ Reusable LeetCode Patterns
DSA with Java — FAANG & Product-Based Interview Questions & Answers (2026)
Master the 25 highest-frequency algorithmic patterns, Java 21 Collections OA traps, Big-O constraint triage, Graphs, and Dynamic Programming questions asked by Google, Amazon, Microsoft, Meta, Uber, Flipkart & Razorpay.
Freshers OA Constraint Triage Q1. How do you deduce the required target Time Complexity directly from input constraint N in a Product-Based OA?
Modern online judges execute ~10^8 simple operations per second in Java. For N <= 20 expect O(2^N) backtracking/bitmask; N <= 500 allows O(N^3) Floyd-Warshall/interval DP; N <= 5,000 allows O(N^2); N <= 2×10^5 requires O(N log N) or O(N); and N <= 10^9–10^18 demands O(log N) binary search, fast exponentiation, or O(1) math.
Freshers Java 21 OA Traps Q2. Why does Scanner cause TLE on large HackerRank Java inputs, and why does Integer == fail above 127?
Scanner uses internal regex parsing that becomes 5–10x slower than BufferedReader + StringTokenizer on 10^5+ lines. Separately, Java caches boxed Integer objects only from -128 to 127; comparing two Integer references with == outside that range compares object identity instead of value — always use .equals() or unbox to primitive int.
Freshers Java Comparator Safety Q3. Why is (a, b) -> a - b dangerous inside Java PriorityQueue or Arrays.sort comparators?
If a = -2,000,000,000 and b = 2,000,000,000, a - b overflows signed 32-bit int and flips sign, violating transitivity and corrupting sort/heap order. Always use Integer.compare(a, b) or Comparator.comparingInt(...), and prefer ArrayDeque over legacy synchronized Stack.
Freshers Prefix Sums & Hashing Q4. How do you count all subarrays whose sum equals K when the array contains negative numbers?
Sliding Window breaks when negative numbers exist because expanding or shrinking is no longer monotonic. Instead, maintain a running prefix sum and a HashMap<Long, Integer> storing prefix frequencies initialized with (0L -> 1); at each index, add map.getOrDefault(prefix - k, 0) to the answer in O(N) time.
Freshers Two Pointers Q5. When should you choose Two Pointers over Hashing, and how do you avoid duplicate triplets in 3Sum?
When input is sorted (or sorting in O(N log N) is allowed) and O(1) auxiliary space is desired, converging left/right pointers solve pair/triplet sums and container problems cleanly. In 3Sum, sort first, skip i when nums[i] == nums[i - 1], and after matching a triplet skip duplicate left and right values.
Freshers Sliding Window Q6. Write the universal O(N) variable-size Sliding Window template in Java for Minimum Window Substring.
Maintain a fixed int[128] frequency balance table and a missing counter; expand right until missing == 0, then greedily contract left while recording the shortest valid window.
O(|S| + |T|) Minimum Window Substring in Java 21java
public String minWindow(String s, String t) {
int[] need = new int[128];
for (char c : t.toCharArray()) need[c]++;
int missing = t.length(), left = 0, bestStart = 0, bestLen = Integer.MAX_VALUE;
for (int right = 0; right < s.length(); right++) {
if (need[s.charAt(right)]-- > 0) missing--;
while (missing == 0) {
if (right - left + 1 < bestLen) {
bestStart = left;
bestLen = right - left + 1;
}
if (++need[s.charAt(left++)] > 0) missing++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen);
}
Freshers Binary Search on Answer Q7. How do you recognize a "Binary Search on Answer Space" problem in Amazon/Google OAs?
Whenever a problem asks to "minimize the maximum" or "maximize the minimum" (e.g., Koko Eating Bananas, Capacity to Ship Packages, Aggressive Cows) and a monotonic predicate feasible(mid) flips once from false to true across [lo, hi], binary search mid = lo + (hi - lo) / 2 in O(N log(Range)) time.
Freshers Sorting Internals Q8. Why can Arrays.sort(int[]) hit O(N^2) on adversarial Java OA test cases while Collections.sort stays O(N log N)?
Java uses Dual-Pivot Quicksort for primitive arrays (int[]), which has known adversarial anti-quicksort inputs in competitive OAs, whereas Object arrays and List/Collections.sort use Timsort with guaranteed O(N log N) worst-case time. Either shuffle primitive arrays first or sort Integer[] when adversarial tests are suspected.
Experienced Linked Lists & Cache Design Q9. How do you implement an O(1) get/put LRU Cache in Java without LinkedHashMap shortcuts?
Pair a HashMap<Integer, Node> with a sentinel-guarded Doubly Linked List (dummy head and tail to eliminate null checks). On get(key), detach the node and insert right after head; on put(key, val), insert/update at head and evict tail.prev whenever size exceeds capacity.
Experienced Monotonic Stack Q10. How does a single Monotonic Stack template unlock Next Greater Element, Daily Temperatures, and Largest Rectangle in Histogram?
Push indices onto an ArrayDeque<Integer> maintaining strictly increasing (or decreasing) heights. Whenever the incoming element breaks monotonicity, pop indices whose boundary has now been discovered — each index is pushed and popped at most once, guaranteeing O(N) time.
O(N) Largest Rectangle in Histogram Using ArrayDequejava
public int largestRectangleArea(int[] heights) {
Deque<Integer> stack = new ArrayDeque<>();
int best = 0, n = heights.length;
for (int i = 0; i <= n; i++) {
int cur = (i == n) ? 0 : heights[i];
while (!stack.isEmpty() && heights[stack.peek()] > cur) {
int h = heights[stack.pop()];
int left = stack.isEmpty() ? -1 : stack.peek();
best = Math.max(best, h * (i - left - 1));
}
stack.push(i);
}
return best;
}
Experienced Monotonic Deque Q11. How do you compute Sliding Window Maximum in O(N) instead of O(N log K)?
Maintain a decreasing ArrayDeque<Integer> of indices: drop front index if it falls outside [i - k + 1, i], pop back indices whose values are <= nums[i] (they can never become the maximum), push i, and read nums[deque.peekFirst()] as the window maximum.
Experienced Backtracking & Pruning Q12. How do you prevent duplicate combinations in Combination Sum II and Permutations II?
Sort the input array first so identical elements sit adjacent. At the same recursion depth, skip index i whenever i > start && nums[i] == nums[i - 1] (or for permutations, skip when nums[i] == nums[i - 1] && !used[i - 1]). Always prune early once remaining target < nums[i].
Experienced Binary Trees & LCA Q13. How do you compute Binary Tree Maximum Path Sum and Lowest Common Ancestor (LCA) in a single O(N) post-order DFS?
In Maximum Path Sum, each DFS call returns the best single downward branch max(0, left/right) + node.val to its parent while updating a global max with node.val + max(0, left) + max(0, right). In LCA, return node if it equals p or q, and if both left and right recursive calls return non-null, node is the LCA.
Experienced Tries & Prefix Search Q14. When does a Bitwise Trie beat a HashMap in FAANG interviews?
For Maximum XOR of Two Numbers (or offline XOR queries <= limit), inserting 31-bit binary representations from MSB to LSB into a 2-child Bitwise Trie lets you greedily pick the opposite bit at each level in O(31) = O(1) time per query — something a HashMap cannot answer efficiently.
Experienced Heaps & Two-Heaps Q15. How do you find the Running Median from a Data Stream in O(log N) per insert?
Maintain a Max-Heap (left half, PriorityQueue<>(Collections.reverseOrder())) and a Min-Heap (right half) such that left.size() == right.size() or left.size() == right.size() + 1. Push into left, move left.poll() to right, and rebalance if right grows larger; median is peek() in O(1).
Experienced Greedy Proof Technique Q16. How do you prove a Greedy choice is optimal in a FAANG interview (e.g., Interval Scheduling vs Jump Game)?
Use an Exchange Argument: show that swapping the first choice of any optimal solution with your greedy choice (e.g., earliest finish time in interval scheduling) never worsens feasibility or objective value. If counterexamples exist (like arbitrary coin denominations), switch to Dynamic Programming.
Experienced Graphs & Topological Sort Q17. Compare Kahn’s BFS Topological Sort vs DFS 3-Color Cycle Detection on Directed Graphs.
Kahn’s algorithm tracks in-degrees in an array and pops zero-indegree nodes from an ArrayDeque; if processed count < V, a cycle exists — ideal for Course Schedule and Lexicographically Smallest ordering (with PriorityQueue). DFS 3-color (0=unvisited, 1=visiting/stack, 2=done) detects a back-edge whenever an edge hits state 1.
System Design Dijkstra & Shortest Paths Q18. Write bug-free Dijkstra’s Algorithm in Java 21 avoiding stale PriorityQueue entries and negative-edge pitfalls.
Always check if (d > dist[u]) continue immediately after polling (lazy deletion) instead of calling O(V) PriorityQueue.remove(). Dijkstra requires non-negative edge weights; for negative weights use Bellman-Ford, and for 0/1 weights use 0-1 BFS with ArrayDeque in O(V + E).
O((V + E) log V) Lazy-Deletion Dijkstra in Java 21java
public long[] dijkstra(int n, List<int[]>[] graph, int src) {
long[] dist = new long[n];
Arrays.fill(dist, Long.MAX_VALUE);
dist[src] = 0;
PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[0]));
pq.offer(new long[]{0L, src});
while (!pq.isEmpty()) {
long[] cur = pq.poll();
long d = cur[0];
int u = (int) cur[1];
if (d > dist[u]) continue;
for (int[] edge : graph[u]) {
int v = edge[0], w = edge[1];
if (d + w < dist[v]) {
dist[v] = d + w;
pq.offer(new long[]{dist[v], v});
}
}
}
return dist;
}
System Design Disjoint Set Union (DSU) Q19. Why does Union-Find with Path Compression and Union by Rank run in O(α(N)) amortized time?
Path compression flattens every visited node along find(x) directly to the root, while Union by Rank/Size always attaches the shallower tree beneath the deeper root. Together, Tarjan proved the amortized cost per operation is the inverse Ackermann function α(N) <= 4 for all practical N — powering Kruskal MST, Accounts Merge, and Dynamic Connectivity.
System Design Tarjan’s Bridges & SCC Q20. How does Tarjan’s Algorithm locate Critical Connections (Bridges) in a network in O(V + E)?
Track discovery time disc[u] and lowest reachable ancestor low[u] during DFS. For any tree edge u -> v, update low[u] = min(low[u], low[v]); if low[v] > disc[u], no back-edge from v’s subtree reaches u or above, proving (u, v) is a critical bridge.
System Design Dynamic Programming Mastery Q21. How do you systematically derive any Dynamic Programming solution from recursion to space-optimized tabulation?
Follow a 4-step pipeline: (1) Define the exact state meaning (e.g., dp[i][j] = min edits for s[0..i) -> t[0..j)), (2) Write base cases and recurrence transition, (3) Add memoization (top-down) to verify correctness, then (4) Convert to bottom-up loops and compress to rolling 1D rows when row i depends only on row i - 1.
System Design Knapsack & Partition DP Q22. Why do you iterate capacity backwards in 0/1 Knapsack 1D DP, but forwards in Unbounded Knapsack / Coin Change?
Iterating w from W down to weight[i] guarantees dp[w - weight[i]] comes from the previous item row (each item used at most once). Iterating w from weight[i] up to W reuses freshly updated values from the current row, allowing unlimited picks of item i.
System Design LIS in O(N log N) Q23. How does Patience Sorting + Binary Search reduce Longest Increasing Subsequence (LIS) from O(N^2) to O(N log N)?
Maintain an array tails where tails[len] stores the smallest possible ending value of an increasing subsequence of length len + 1. For each x, binary search the leftmost tails[idx] >= x (lower_bound) and replace it; the final length of tails equals the exact LIS length.
System Design Bitmask & Digit DP Q24. When do you reach for Bitmask DP or Digit DP in Google / CodeSignal Hard rounds?
Use Bitmask DP whenever subset state N <= 20 (e.g., Traveling Salesman, Assign Tasks to Workers, Partition into K Equal Subsets) representing visited sets as an int mask (1 << N). Use Digit DP for counting integers in [L, R] obeying digit properties via memoized state (pos, tight, leadingZero, extraState).
System Design Fenwick Tree (BIT) & Segment Tree Q25. Compare Fenwick Tree (BIT) vs Segment Tree for Range Queries with Point/Range Updates in Java.
Fenwick Tree (BIT) uses ~15 lines of code, 1×N memory, and blazingly fast i += i & -i bit ops for invertible prefix queries (sums, Count of Smaller Numbers After Self). Segment Tree handles non-invertible operations (range min/max/GCD) and supports O(log N) Range Updates via Lazy Propagation.
Compact O(log N) Fenwick Tree (Binary Indexed Tree) in Javajava
class FenwickTree {
private final long[] bit;
FenwickTree(int n) { this.bit = new long[n + 1]; }
void add(int idx, long delta) {
for (int i = idx + 1; i < bit.length; i += i & -i) bit[i] += delta;
}
long prefixSum(int idx) {
long sum = 0;
for (int i = idx + 1; i > 0; i -= i & -i) sum += bit[i];
return sum;
}
long rangeSum(int l, int r) { return prefixSum(r) - (l > 0 ? prefixSum(l - 1) : 0); }
}