How to Use This Guide
Most interview failures come not from not knowing an algorithm, but from failing to recognise which pattern applies. This guide trains the recognition reflex: read the problem → spot the keyword cluster → map to a pattern → implement.
The Recognition Loop
Step 1: Read the problem statement. Underline the constraints (sorted? distinct? in-place? shortest? count?).
Step 2: Match keywords against the pattern table below.
Step 3: State the pattern out loud: "I think this is a [sliding window / BFS / DP] problem because..."
Step 4: Verify with a small example before coding. Write the template, then fill in problem-specific logic.
Master Pattern Table
| Pattern | Keywords in Problem | Time | Key Data Structure |
|---|---|---|---|
| Two Pointer | sorted array, pair sum, palindrome, in-place reverse | \(O(n)\) | Array (two indices) |
| Sliding Window | subarray/substring, contiguous, longest/shortest, window | \(O(n)\) | Deque or hashmap |
| BFS | shortest path, level-order, minimum steps, unweighted graph | \(O(V + E)\) | Queue (deque) |
| DFS | all paths, connected components, cycle detection, count ways | \(O(V + E)\) | Stack / recursion |
| Backtracking | all combinations/permutations, generate, find all solutions | \(O(2^n)\) or \(O(n!)\) | Recursion + visited set |
| Binary Search on Answer | minimum/maximum possible value, feasibility, "if you can do X" | \(O(n \log n)\) | Array (sorted answer space) |
| Monotonic Stack | next/previous greater/smaller, histogram, temperature | \(O(n)\) | Stack |
| Monotonic Deque | sliding window max/min | \(O(n)\) | Deque |
| Heap (Top-K) | K largest/smallest/closest, median, priority | O(n log K) | Min/max heap |
| 1D DP | maximize/minimize with 1 variable, climb stairs, coin change | \(O(n)\) | Array dp[n] |
| 2D DP | grid path, edit distance, LCS, string comparison | \(O(n \times m)\) | Matrix dp[n][m] |
| Interval DP | merge intervals, burst balloons, matrix chain | \(O(n^2)\) or \(O(n^3)\) | dp[i][j] |
| Union-Find | connected components, merge groups, number of islands | \(O(\alpha(n))\) | DSU array |
| Trie | prefix, autocomplete, word search, XOR | \(O(L)\) | Trie nodes |
Two Pointer
Use two pointers when the array is sorted (or can be) and you're looking for pairs or palindromic properties. The pointers move toward each other or in the same direction (fast/slow).
Template: Two-Sum on Sorted Array
Keywords: sorted array, find pair with sum = target, no extra space.
Canonical problems: Two Sum II (167), Container With Most Water (11), 3Sum (15), Valid Palindrome (125), Trapping Rain Water (42).
Sliding Window
Sliding window solves "find longest/shortest subarray/substring satisfying condition X" in \(O(n)\). Expand right until condition violated; shrink left until condition restored.
Template: Longest Substring with At Most K Distinct Characters
Canonical problems: Minimum Window Substring (76), Longest Substring Without Repeating Characters (3), Sliding Window Maximum (239), Permutation in String (567).
BFS vs DFS Decision
| Question | Use BFS | Use DFS |
|---|---|---|
| Shortest path (unweighted)? | Yes | No |
| Find if any path exists? | Either | Yes (simpler) |
| Count all paths? | No | Yes (backtracking) |
| Topological order? | Kahn's (BFS) | Post-order DFS |
| Detect cycle? | Either | Yes (DFS colors) |
| Tree level order? | Yes (natural) | Need explicit level tracking |
Backtracking Template
Universal Backtracking Template
Canonical problems: Subsets (78), Permutations (46), Combination Sum (39), N-Queens (51), Word Search (79), Sudoku Solver (37).
Dynamic Programming Patterns
DP works when the problem has: (1) optimal substructure — optimal solution contains optimal solutions to subproblems, and (2) overlapping subproblems — same subproblems recur many times.
1D DP Template: Coin Change
2D DP: Edit Distance
2D DP problems have state defined by two variables — typically two indices into strings, or row/column in a grid. The canonical examples are Longest Common Subsequence (build up matching characters from two sequences) and Edit Distance (minimum insertions, deletions, or substitutions to transform one string into another). The recurrence relates \(dp[i][j]\) to its neighbors: \(dp[i-1][j]\), \(dp[i][j-1]\), and \(dp[i-1][j-1]\), corresponding to the three possible operations.
Longest Common Subsequence (LeetCode 1143)
Interval DP: Burst Balloons
Burst Balloons (LeetCode 312)
Think: which balloon is burst last in a range [i, j]? dp[i][j] = max coins from range i..j.
Monotonic Stack
Use when the problem asks: "for each element, find the nearest element to the left/right that is greater/smaller." Every element enters and exits the stack exactly once — \(O(n)\) total.
Next Greater Element (LeetCode 496)
Canonical problems: Next Greater Element (496, 503), Daily Temperatures (739), Largest Rectangle in Histogram (84), Trapping Rain Water (42).
Binary Search on Answer
Use when the problem asks for "minimum/maximum value such that a condition holds". Binary search the answer space, check feasibility with a helper function.
Koko Eating Bananas (LeetCode 875)
Canonical problems: Search Insert Position (35), Find Peak Element (162), Koko Eating Bananas (875), Split Array Largest Sum (410), Capacity to Ship (1011).
Heap — Top-K Pattern
Any problem asking for the "K largest", "K closest", "K most frequent", or "Kth element" maps to a heap of size K. The strategy: maintain a min-heap of size K — when a new element is larger than the heap's minimum, replace it. After processing all elements, the heap contains the top-K. This gives \(O(n \log k)\) time, which is optimal when \(k \ll n\) since you avoid fully sorting the entire array.
K Closest Points to Origin (LeetCode 973)
Canonical problems: K Closest Points (973), Top K Frequent Elements (347), Kth Largest Element (215), Merge K Sorted Lists (23), Median from Data Stream (295).
The 45-Minute Interview Framework
Time Budget
| Time | Activity | What to Say |
|---|---|---|
| 0–5 min | Clarify constraints | "Is the array sorted? Can it have duplicates? What's the expected input size?" |
| 5–10 min | Pattern recognition + brute force | "My first thought is \(O(n^2)\) brute force... but I recognise this as a [pattern] problem, which should give \(O(n)\)." |
| 10–12 min | Verify approach with small example | Trace through 3–4 elements manually. Catch edge cases. |
| 12–35 min | Code | Write clean code with meaningful variable names. Talk through each step. |
| 35–40 min | Test | Run through your example, then edge cases: empty input, single element, all same, sorted, reverse-sorted. |
| 40–45 min | Complexity analysis | "Time: \(O(n \log n)\) because... Space: \(O(n)\) because... Could we reduce space to \(O(1)\) by...?" |
Common Interview Mistakes
- Coding without clarifying: Always ask about constraints before touching the keyboard.
- Jumping to optimal immediately: State brute force first, then optimise. Interviewers want to see your reasoning process.
- Silent coding: Think out loud. If you're stuck, say "I'm thinking about whether I can use X here..."
- Forgetting edge cases: Always test empty input and single-element input.
- Wrong complexity claim: If you say \(O(n)\), know exactly why. Interviewers probe this.