Patterns

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.

01
Section One Β· Framework

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.

The 5-Step Framework
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
The biggest interview mistake is skipping step 3.:
  • 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.
02
Section Two Β· Signal Map

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 β†’
Multiple signals?:
  • 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.
03
Section Three Β· Prefix Sum

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).

Template
// Build prefix sum β€” O(n) int[] prefix = new int[n + 1]; for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + arr[i]; // Range sum [l, r] β€” O(1) int rangeSum = prefix[r + 1] - prefix[l]; // Subarray sum equals k β€” O(n) with HashMap Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); // empty prefix int sum = 0, count = 0; for (int x : arr) { sum += x; count += map.getOrDefault(sum - k, 0); // how many prefixes equal sum-k? map.merge(sum, 1, Integer::sum); }
  • 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 - k was seen before.
  • Medium prefix Product of Array Except Self β€” LC 238 β€” Prefix product from left Γ— suffix product from right.
04
Section Four Β· Monotonic Stack

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).

Template β€” Next Greater Element
// Decreasing stack β€” finds next GREATER element for each index int[] result = new int[n]; Arrays.fill(result, -1); // default: no greater element Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i < n; i++) { while (!stack.isEmpty() && arr[stack.peek()] < arr[i]) { result[stack.pop()] = arr[i]; // arr[i] is the next greater } stack.push(i); // O(n) total β€” each index pushed/popped once }
Decreasing Stack

Finds NEXT GREATER

Pop when incoming element is LARGER than stack top. The popped element's "next greater" is the incoming element.

Increasing Stack

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).
05
Section Five Β· Union-Find

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

Template
class UnionFind { int[] parent, rank; int components; UnionFind(int n) { parent = new int[n]; rank = new int[n]; components = n; for (int i = 0; i < n; i++) parent[i] = i; } int find(int x) { if (parent[x] != x) parent[x] = find(parent[x]); // path compression return parent[x]; } boolean union(int x, int y) { int px = find(x), py = find(y); if (px == py) return false; // already connected if (rank[px] < rank[py]) { int t = px; px = py; py = t; } parent[py] = px; // union by rank if (rank[px] == rank[py]) rank[px]++; components--; return true; } }
Union-Find vs DFS for connected components:
  • 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.
06
Section Six Β· Bit Manipulation

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.

Essential Bit Tricks
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 use Integer.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.
07
Section Seven Β· Intervals

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.

Template β€” Merge Intervals
Arrays.sort(intervals, (a, b) -> a[0] - b[0]); // sort by start List<int[]> merged = new ArrayList<>(); for (int[] iv : intervals) { if (merged.isEmpty() || merged.getLast()[1] < iv[0]) merged.add(iv); // no overlap β€” new interval else merged.getLast()[1] = Math.max(merged.getLast()[1], iv[1]); // merge }
Sort by START

Merge / Insert Intervals

Merge overlapping ranges, insert a new interval into a sorted list.

Sort by END

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.
08
Section Eight Β· Practice Plan

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.
The 3-pass method:
  • 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.
Final thought: Interview patterns are like chess openings β€” there are only ~15, and once you know them, every game starts from a familiar position. You don't need to solve 500 problems. You need to deeply understand 50, one from each sub-pattern, until you can recognise the pattern from the problem statement alone. That's the skill interviews test: pattern recognition, not memorisation.