Interview Patterns Cheat Sheet
Every coding interview problem maps to one of ~15 patterns. Recognise the signal, pick the pattern, write the template. This page is three things: a problem-solving framework, a signalβpattern cheat sheet, and deep dives on the patterns not covered in their own pages.
How to Approach Any Problem
Every interview problem can be solved with the same 5-step process. The steps take 2β3 minutes of thinking before you write a single line of code β and they prevent the most common interview failure: jumping into code without a plan.
| Step | Time | What You Do | Output |
|---|---|---|---|
| 1. Understand | 1 min | Restate the problem. Clarify edge cases: empty input? negative numbers? duplicates? Confirm return type. | Clear problem statement + constraints |
| 2. Examples | 1 min | Walk through 1β2 examples by hand. Include an edge case (empty, single element, all same). | Worked examples showing expected output |
| 3. Pattern | 1 min | Identify the pattern using the signal map (next section). State the approach out loud: "This is a sliding window problem because..." | Named pattern + high-level approach |
| 4. Code | 15β20 min | Write clean code. Use descriptive variable names. Talk through each line as you write. | Working solution |
| 5. Test | 2β3 min | Trace through your code with the examples. Check edge cases. Analyse time and space complexity. | Verified solution + O(?) analysis |
- If you start coding without identifying the pattern, you'll either pick the wrong approach (and have to restart), or implement a brute-force solution and run out of time optimising.
- Spend 60 seconds on pattern recognition β it saves 10 minutes of wasted coding.
Signal β Pattern Cheat Sheet
Read the problem statement. Look for these signals. Each signal maps to exactly one pattern (or a small set of candidates). This table covers every common interview pattern β the ones with dedicated pages and the ones covered below.
| Signal in Problem | Pattern | Page |
|---|---|---|
| "sorted array" + "find pair / target sum" | Two Pointers (opposite ends) | β |
| "contiguous subarray" + "sum/count/max length" | Sliding Window | β |
| "sorted" + "find target / boundary / first/last" | Binary Search | β |
| "minimise the maximum" / "find min speed/capacity" | Binary Search on Answer | β |
| "remove in-place" / "compact" / "O(1) space filter" | Two Pointers (read/write) | β |
| "linked list cycle" / "middle of list" | Fast & Slow Pointers | β |
| "shortest path / minimum steps" (unweighted) | BFS | β |
| "detect cycle" / "connected components" / "topological order" | DFS | β |
| "prerequisites" / "dependencies" / "ordering constraints" | Topological Sort | β |
| "minimum cost/time" (weighted) / "cheapest flight with K stops" | Shortest Path (Dijkstra / Bellman-Ford) | β |
| "count ways" / "min cost" / "can you partition/make amount" | Dynamic Programming | β |
| "subarray sum equals k" / "range sum query" | Prefix Sum | β Β§3 |
| "next greater/smaller element" / "largest rectangle" | Monotonic Stack | β Β§4 |
| "all subsets / permutations / combinations" / "N-Queens" | Backtracking | β |
| "interval scheduling" / "earliest deadline" / "locally optimal" | Greedy | β |
| "dynamic connectivity" / "group merging" / "are X and Y connected" | Union-Find | β Β§5 |
| "single number" / "power of two" / "bit count" / "XOR trick" | Bit Manipulation | β Β§6 |
| "merge intervals" / "meeting rooms" / "overlapping ranges" | Intervals (sort + merge/sweep) | β Β§7 |
| "top K / kth largest / stream median" | Heap | β |
| "autocomplete / prefix search / word search" | Trie | β |
- Some problems combine patterns: "sorted array + range sum" = prefix sum + binary search. "All paths in a grid" = DFS + backtracking. "Minimum spanning tree" = greedy + union-find.
- When you see two signals, combine the patterns.
Prefix Sum
Build an auxiliary array where prefix[i] = sum of elements from index 0 to i-1. Any subarray sum arr[l..r] becomes prefix[r+1] - prefix[l] in O(1). This transforms range sum queries from O(n) per query to O(1) per query after O(n) preprocessing. Combined with a HashMap, it solves "subarray sum equals k" (LC 560) in O(n).
- Easy prefix Running Sum of 1D Array β LC 1480 β Pure prefix sum construction.
- Medium prefix+hash Subarray Sum Equals K β LC 560 β Prefix sum + HashMap: count prefixes where
prefix - kwas seen before. - Medium prefix Product of Array Except Self β LC 238 β Prefix product from left Γ suffix product from right.
Monotonic Stack
A stack that maintains a monotonic order (always increasing or always decreasing from bottom to top). When pushing an element, pop all elements that violate the monotonic property β the popped elements have just found their "next greater" or "next smaller" element. This solves "next greater element" (LC 496/503), "daily temperatures" (LC 739), and "largest rectangle in histogram" (LC 84) in O(n).
Finds NEXT GREATER
Pop when incoming element is LARGER than stack top. The popped element's "next greater" is the incoming element.
Finds NEXT SMALLER
Pop when incoming element is SMALLER than stack top. The popped element's "next smaller" is the incoming element.
- Easy mono-stack Next Greater Element I β LC 496 β Decreasing stack on the second array + HashMap for lookup.
- Medium mono-stack Daily Temperatures β LC 739 β Decreasing stack of indices. When popped, distance = i - popped index.
- Hard mono-stack Largest Rectangle in Histogram β LC 84 β Increasing stack. When popped, compute area with popped height Γ (right boundary - left boundary).
Union-Find (Disjoint Set)
Union-Find maintains a collection of disjoint sets supporting two operations: find(x) β which set does x belong to? and union(x, y) β merge the sets containing x and y. With path compression and union by rank, both operations run in amortised O(Ξ±(n)) β O(1). Union-Find is the tool for dynamic connectivity β when edges are added incrementally and you need to check "are x and y in the same component?"
- For a static graph (all edges known upfront), DFS is simpler and equally fast.
- Union-Find shines when edges arrive dynamically (one at a time) or when you need to track component count as merges happen β problems like "Number of Connected Components" (LC 323) and "Redundant Connection" (LC 684).
- Medium union-find Number of Provinces β LC 547 β Union all friends. Component count = number of provinces.
- Medium union-find Redundant Connection β LC 684 β Process edges in order. First edge where union returns false (already connected) = the redundant edge.
- Medium union-find Accounts Merge β LC 721 β Union emails by account. Group by root to merge accounts.
Bit Manipulation
Bit manipulation uses bitwise operators (&, |, ^, ~, <<, >>) to solve problems in O(1) space and often O(n) or O(1) time. The key insight: XOR (^) cancels identical values β a ^ a = 0 and a ^ 0 = a. This is why "find the single number" (LC 136) is solvable by XORing all elements. Other common tricks: n & (n-1) removes the lowest set bit (useful for counting bits), and n & (-n) isolates the lowest set bit.
| Operation | Code | What it does |
|---|---|---|
| Check if power of 2 | n > 0 && (n & (n-1)) == 0 | Powers of 2 have exactly one set bit |
| Count set bits | Integer.bitCount(n) | Built-in popcount β O(1) |
| Remove lowest set bit | n & (n - 1) | Brian Kernighan's trick |
| Isolate lowest set bit | n & (-n) | Useful in Binary Indexed Tree |
| Check if bit i is set | (n >> i) & 1 | Shift right then mask |
| Set bit i | n | (1 << i) | OR with mask |
| Clear bit i | n & ~(1 << i) | AND with inverted mask |
| XOR all elements | for (x : arr) xor ^= x | Duplicates cancel out β single element remains |
- Easy bits Single Number β LC 136 β XOR all elements. Pairs cancel to 0, leaving the unique one.
- Easy bits Number of 1 Bits β LC 191 β
n & (n-1)loop, count iterations. Or useInteger.bitCount(n). - Medium bits Counting Bits β LC 338 β dp[i] = dp[i & (i-1)] + 1 β remove lowest bit, add one.
- Medium bits Single Number III β LC 260 β XOR all to get a^b. Use lowest differing bit to split into two groups, XOR each group.
Interval Problems
Interval problems involve ranges [start, end]. Almost all of them start with the same step: sort by start time (or end time for scheduling). Then sweep left to right, merging overlapping intervals, counting conflicts, or inserting new intervals. The mental model: intervals on a number line, sorted so you process them left to right.
Merge / Insert Intervals
Merge overlapping ranges, insert a new interval into a sorted list.
Scheduling / Min Removals
Pick the earliest-ending interval first. Greedy activity selection.
- Medium intervals Merge Intervals β LC 56 β Sort by start. Merge if current.start β€ prev.end.
- Medium intervals Insert Interval β LC 57 β Find insertion point, merge overlapping, collect non-overlapping.
- Medium intervals Meeting Rooms II β LC 253 β Min-heap of end times. For each meeting, if it starts after the earliest end, reuse that room; else add a new room.
The 50-Problem Practice Plan
If you solve 50 well-chosen problems β 3β5 per pattern β you'll recognise every interview pattern. Quality over quantity: understand WHY a pattern applies, not just HOW to code it. Here's a curated order that builds each pattern on the previous:
| Week | Pattern | Problems |
|---|---|---|
| 1 | Array + Hashing | Two Sum, Contains Duplicate, Group Anagrams, Top K Frequent, Product Except Self |
| 2 | Two Pointers + Sliding Window | Valid Palindrome, 3Sum, Container, Longest Without Repeat, Min Window Substring |
| 3 | Stack + Binary Search | Valid Parentheses, Daily Temperatures, Binary Search, Search Rotated, Koko Bananas |
| 4 | Linked List + Trees | Reverse LL, Merge Two, Cycle II, Max Depth, Level Order, Validate BST |
| 5 | Trees + Heap | LCA, Serialize/Deserialize, Kth Largest Stream, Merge K Lists, Top K Frequent |
| 6 | Graphs (BFS + DFS) | Num Islands, Clone Graph, Course Schedule, Pacific Atlantic, Word Ladder |
| 7 | Backtracking + Greedy | Subsets, Permutations, Combination Sum, Jump Game, Non-overlapping Intervals |
| 8 | Dynamic Programming | Climbing Stairs, House Robber, Coin Change, LIS, LCS, Edit Distance |
| 9 | Intervals + Union-Find + Bits | Merge Intervals, Meeting Rooms II, Redundant Connection, Single Number, Counting Bits |
| 10 | Mixed + Review | Random medium/hard problems. Time yourself. Practice the 5-step framework end-to-end. |
- Pass 1 β solve with hints (learn the pattern). Pass 2 β solve without hints (memorise the template).
- Pass 3 β solve timed under 25 minutes (build speed).
- If you can't solve a problem in 20 minutes, read the solution, understand it, then re-solve from scratch the next day.