Coding Interview Patterns Cheatsheet: 15 Templates That Solve LeetCode
Skip the grind. These 15 reusable patterns cover 90% of LeetCode problems and will get you through any FAANG-level coding interview.
Coding Interview Patterns Cheatsheet: 15 Templates That Solve LeetCode
Most engineers approach LeetCode wrong. They grind 300+ problems randomly, panic when they see something unfamiliar, and walk into interviews hoping brute force plus clever naming will carry them through. It won't. The engineers who consistently pass FAANG-level screens don't know more problems — they recognize more patterns. Once you internalize that "find the subarray with max sum" and "find the longest substring without repeating characters" are the same problem wearing different hats, your hit rate jumps dramatically. This guide gives you the 15 pattern templates that cover the overwhelming majority of what Amazon, Google, Meta, and Microsoft will actually throw at you in 2026.
"You don't need to solve 500 LeetCode problems. You need to solve 50 problems 10 different ways until the pattern is automatic."
Each template below includes what it solves, the signal that tells you to use it, and the skeleton logic you should have memorized cold.
Pattern 1–3: Array and String Manipulation Are 30% of Your Interview
Arrays and strings aren't "easy" topics — they're the highest-frequency topics. Interviewers use them to test whether you think algorithmically before you reach for brute force.
1. Two Pointers Use when: sorted array, pairs summing to target, palindrome checks, container problems. Skeleton: initialize left = 0, right = n - 1, move them toward each other based on a condition. You eliminate O(n²) brute force down to O(n) in one move.
2. Sliding Window Use when: "subarray" or "substring" with a size constraint or an optimization (max, min, longest, shortest). Fixed window = move both pointers together. Variable window = expand right, shrink left when the constraint is violated. The tell: if the problem says "contiguous" and asks for an optimum, it's sliding window.
3. Prefix Sum Use when: range sum queries, subarray sum equals k, counting subarrays with a property. Precompute prefix[i] = prefix[i-1] + nums[i]. Range sum from i to j = prefix[j] - prefix[i-1]. Combine with a hashmap to find subarray sum equals k in O(n).
These three alone handle problems like Best Time to Buy and Sell Stock, Longest Substring Without Repeating Characters, Subarray Sum Equals K, and Container With Most Water. That's four of the top-20 most-asked problems right there.
Pattern 4–6: Tree and Graph Problems Reward One Insight
Every tree problem reduces to a traversal decision. Every graph problem reduces to a search decision. Make the right choice first and the code practically writes itself.
4. DFS on Trees (Recursive) Use when: path problems, depth, diameter, lowest common ancestor, validating BST properties. The template: base case returns a sentinel (null → 0 or null), recurse left and right, combine results at current node. Max depth, path sum, diameter — same three lines of recursion, different combination logic.
5. BFS (Level-Order Traversal) Use when: shortest path in an unweighted graph, level-by-level tree processing, "minimum steps" problems. Use a queue. Enqueue the root/start, process level by level, track visited nodes in a set. The moment a problem says "minimum" and the graph is unweighted, reach for BFS before anything else.
6. Union-Find (Disjoint Set Union) Use when: dynamic connectivity, number of connected components, detecting cycles in undirected graphs, "accounts merge" style grouping problems. Implement with path compression and union by rank — both are required for O(α(n)) amortized time. Without them, you're writing O(n) find operations and an interviewer will notice.
Pattern 7–9: Dynamic Programming Has Exactly Four Shapes
DP has a reputation for being unpredictable. That reputation is undeserved. Nearly every DP problem you'll see at interview is one of four shapes. Learn the shapes.
7. 1D DP (Linear Sequence) Use when: Fibonacci variants, climbing stairs, house robber, decode ways. dp[i] depends on dp[i-1] and/or dp[i-2]. This can almost always be space-optimized to two variables instead of an array. Always mention this optimization — interviewers reward it.
8. 2D DP (Grid or Two-Sequence) Use when: longest common subsequence, edit distance, unique paths, coin change with two variables. Build a 2D table where dp[i][j] represents the answer for the first i elements of one input and j elements of another. The recurrence lives at the intersection of two choices: include or exclude, match or skip.
9. Knapsack / Subset DP Use when: partition equal subset sum, target sum, 0/1 knapsack, combination sum IV. The tell is that you're deciding whether to include each item. dp[i][w] = can we achieve weight w using items 0..i. Optimize to 1D by iterating the capacity dimension in reverse.
"The difference between a candidate who 'knows DP' and one who can actually solve DP problems under pressure is pattern recognition, not intelligence."
Pattern 10–12: Heaps, Binary Search, and Monotonic Stacks Are the Separators
These three patterns separate the candidates who clear phone screens from the ones who make it to onsites. They appear in medium and hard problems specifically because most candidates don't think to reach for them.
10. Heap (Priority Queue) Use when: K largest/smallest elements, merge K sorted lists, median of a data stream, task scheduling. Two-heap pattern for the median problem: max-heap for the lower half, min-heap for the upper half, rebalance after each insertion. Single min-heap for K largest (counterintuitive but correct — evict the smallest).
11. Binary Search on the Answer Use when: the problem has a monotonic condition and asks you to minimize or maximize a value. The tell is subtle: "minimum speed to arrive on time," "minimum capacity to ship packages," "koko eating bananas." These aren't searching a sorted array — they're searching a range of possible answers. Template: lo = min_possible, hi = max_possible, mid = (lo + hi) // 2, check feasibility of mid, adjust bounds.
12. Monotonic Stack Use when: next greater element, largest rectangle in histogram, daily temperatures, trapping rain water. Maintain a stack that is always increasing or always decreasing. When the current element violates the order, pop and process. This converts O(n²) naive solutions to O(n) and it's one of the most underused patterns in interview prep.
Pattern 13–15: The Advanced Patterns That Signal Senior-Level Thinking
If you're targeting senior or staff roles — Principal Engineer, Tech Lead, L6+ — you will see harder problems. These three patterns show up in hard LeetCode and in the system-design-adjacent coding questions that senior loops include.
13. Trie (Prefix Tree) Use when: autocomplete, word search, prefix matching, replace words. Implement a TrieNode with a children map and an is_end flag. Insert, search, and startsWith are all O(L) where L is word length. Interviewers ask Trie problems specifically to see if you can implement a custom data structure cleanly under pressure.
14. Topological Sort Use when: dependency ordering, course schedule, build systems, any "finish A before B" constraint. Two valid implementations: BFS Kahn's algorithm (use in-degree array, enqueue zero-in-degree nodes) or DFS with a visited/processing/done state. Detect cycles: if BFS result doesn't include all nodes, a cycle exists.
15. Backtracking Use when: all permutations, all subsets, N-Queens, Sudoku solver, word search in a grid. Template: make a choice, recurse, undo the choice. The pruning conditions are what separate an O(n!) solution that times out from one that passes. Always identify early termination conditions before you start coding.
How to Actually Use These Patterns in an Interview
Knowing the patterns abstractly isn't enough. Here's the decision sequence that high-performing candidates use in real interviews:
- Read the problem once fully before writing a single character.
- Identify the input type: array/string, tree/graph, or abstract (DP/heap).
- Ask yourself: does the problem involve a contiguous substructure? → Sliding window or prefix sum. Shortest path? → BFS. Optimization over a sequence? → DP. Top K? → Heap.
- State the pattern out loud: "I think this is a sliding window problem because we're looking for a contiguous substring with a constraint."
- Write the skeleton before filling in problem-specific logic.
- Handle edge cases last, not first.
The verbal step (step 4) is critical. Interviewers are not just evaluating your solution — they're evaluating your thinking. A candidate who says "I recognize this as a two-pointer problem" before writing anything signals experience. A candidate who silently writes a nested loop signals otherwise.
The Honest Truth About How Many Problems You Actually Need to Practice
The internet will tell you to grind 150, 300, or 500 problems. Here's the real breakdown for a senior-level candidate targeting companies like Amazon, Google, or Shopify in 2026:
- Two Pointers / Sliding Window: 8–10 problems, then you've seen every variation
- BFS/DFS: 10–12 problems covering trees and graphs separately
- Dynamic Programming: 15–20 problems, distributed across all four shapes
- Heap / Binary Search: 6–8 problems each
- Backtracking: 5–6 problems
- Trie / Union-Find / Topological Sort: 3–4 problems each
That's roughly 70–90 problems done deliberately — meaning you understand why the pattern applies, not just that it does. Compare that to grinding 300 problems randomly and wondering why you still blank on interviews. Quality over volume is not a soft platitude here; it's a measurable strategy.
For salary context: senior engineers passing these screens at Amazon, Google, or Shopify in Vancouver are landing $180K–$280K CAD total compensation in 2026, with staff/principal roles at top companies pushing beyond $350K CAD. The interview prep investment is worth it.
What to Memorize Cold Versus What to Derive
Not everything needs to be memorized. Here's the honest breakdown:
Memorize cold (you cannot derive these under pressure):
- Union-Find with path compression
- Trie node implementation
- Kahn's topological sort (BFS variant)
- The two-heap pattern for the running median
- Knapsack 1D space optimization direction (reverse iteration)
Derive from first principles in the room:
- Any DFS/BFS traversal (the structure is always the same)
- Sliding window expansion/contraction logic
- Binary search bounds (derive from the problem's feasibility condition)
- Backtracking choice/unchoice structure
If you try to memorize binary search implementations, you will write it wrong under pressure because there are four valid variants. Instead, understand why you move lo versus hi and derive it each time. If you try to derive Union-Find from scratch in 45 minutes, you'll run out of time. Know the difference.
Next Steps
Here are five concrete actions to take in the next week:
- Audit your weak patterns. Go through the 15 patterns above and rate yourself 1–3 on each. Be honest. Anything rated 1 or 2 goes on a focused practice list before you touch anything else.
- Do one problem per pattern in the next 7 days. Pick a medium-difficulty problem for each pattern you rated yourself low on. Don't time yourself yet — focus on pattern recognition and clean implementation.
- Write out your pattern templates by hand. Union-Find, Trie, Kahn's sort, two-heap median. Write them without looking. If you can't, you don't know them well enough to use them under interview pressure.
- Practice the verbal step. On your next 5 practice problems, before writing code, say out loud (yes, out loud) which pattern applies and why. This builds the habit for live interviews where silence is expensive.
- Time yourself starting next week. Once you can consistently identify and implement a pattern correctly, add a 35-minute timer. Most phone screens are 45 minutes with setup time — 35 minutes of actual coding time is realistic. If you can't finish and test a medium problem in 35 minutes, that's the constraint to fix before you apply anywhere.
Related guides
- LeetCode Patterns Cheatsheet: 15 Templates That Solve 80% of Problems — Stop grinding blindly. These 15 reusable patterns cover the vast majority of LeetCode problems and will cut your prep time in half.
- SQL Interview Patterns Cheatsheet — Joins, Subqueries, and the 10 Templates That Recur — A SQL interview patterns cheatsheet built around the recurring templates: joins, anti-joins, aggregation, top-N per group, window functions, subqueries, deduplication, retention, funnels, and data-quality checks. Use it to recognize the prompt before you write the query.
- API Design Interview Cheatsheet in 2026 — Patterns, Examples, Practice Plan, and Common Traps — A practical API design interview cheatsheet for 2026: how to scope the problem, choose REST/GraphQL/gRPC patterns, model resources, handle auth, versioning, rate limits, and avoid the traps that cost senior candidates offers.
- AWS Interview Cheatsheet in 2026 — Patterns, Examples, Practice Plan, and Common Traps — A high-signal AWS interview cheatsheet for 2026 covering architecture patterns, IAM, networking, reliability, cost, debugging, and the answers that show real cloud judgment.
- Backend System Design Interview Cheatsheet in 2026 — Patterns, Examples, Practice Plan, and Common Traps — A backend System Design interview cheatsheet for 2026 with the core flow, architecture patterns, capacity heuristics, reliability tradeoffs, and traps that separate senior answers from vague box drawing.
