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.
LeetCode Patterns Cheatsheet: 15 Templates That Solve 80% of Problems
Most engineers approach LeetCode wrong. They grind 300+ random problems, burn out, and still freeze when they see an unfamiliar question in the interview room. The smarter approach is pattern recognition — learning the 15 underlying templates that appear, in one form or another, in the overwhelming majority of algorithm problems. Once you internalize these, you stop solving problems and start categorizing them, which is infinitely faster and more reliable under pressure.
This guide is built for engineers preparing for FAANG and FAANG-adjacent interviews in 2026. Whether you're a senior engineer targeting a principal role or an SWE-2 doing your first big tech loop, these patterns are your foundation. At companies like Amazon, Google, and Meta, interview difficulty has stabilized at a medium-to-hard LeetCode ceiling — and every single problem at that level maps to one of the templates below.
"The candidate who recognizes the pattern in the first 60 seconds wins the interview. The candidate who stares at constraints hoping for inspiration loses it."
Pattern Recognition Is the Actual Skill Interviewers Are Testing
Before the templates, understand what's really happening in a coding interview. Your interviewer is not checking whether you memorized a specific solution. They are checking whether you can decompose an ambiguous problem into a known structure and execute cleanly under pressure. That means the meta-skill — recognizing which pattern applies — is more valuable than deeply knowing any individual algorithm.
When you see a problem, your first 60 seconds should be spent on classification, not coding. Ask yourself: Is this a traversal problem? An optimization problem? Does it involve a sorted array? A graph? Constraints matter too: an O(n²) sliding window won't fly if n is 10⁶. Constraint reading is part of the pattern-matching game.
The 15 Core Patterns (With When to Use Each)
Here they are, in rough order of interview frequency:
- Two Pointers — Use when the input is sorted or when you need to find pairs/triplets that satisfy a condition. Classic problems: Two Sum (sorted), 3Sum, Container With Most Water. Template: left pointer at index 0, right at index n-1, converge based on comparison.
- Sliding Window — Use for subarray/substring problems asking for max, min, or count with a size or value constraint. Classic problems: Longest Substring Without Repeating Characters, Minimum Window Substring. Fixed-size vs. variable-size windows are two subtypes — know both.
- Fast & Slow Pointers (Floyd's Cycle) — Use for linked list cycle detection or finding the middle of a list. Classic problems: Linked List Cycle, Find Duplicate Number. The slow pointer moves 1 step, fast moves 2 — they meet if a cycle exists.
- Merge Intervals — Use when the input is a list of intervals and you need to merge, insert, or find overlaps. Classic problems: Merge Intervals, Insert Interval, Meeting Rooms II. Sort by start time, then iterate and compare current end with next start.
- Binary Search on Answer — Use when you can ask "is X achievable?" as a yes/no question and the answer space is monotonic. Classic problems: Koko Eating Bananas, Capacity to Ship Packages. This is one of the most underused templates — medium/hard problems disguise it constantly.
- BFS (Level-Order Traversal) — Use for shortest path in unweighted graphs, or when level-by-level processing matters. Classic problems: Binary Tree Level Order Traversal, Word Ladder, Rotting Oranges. Always reach for a queue. If you need shortest path in a weighted graph, reach for Dijkstra instead.
- DFS / Backtracking — Use for exhaustive exploration: generating permutations, combinations, subsets, or solving constraint satisfaction problems like N-Queens and Sudoku. The template: recurse with a choice, undo the choice (backtrack), try next option. This pattern is 30% of the medium-to-hard problem set at top companies.
- Dynamic Programming (Top-Down with Memoization) — Use when the problem has overlapping subproblems and optimal substructure. Classic problems: Coin Change, Longest Common Subsequence, 0/1 Knapsack. If you can't see the bottom-up recurrence immediately, write the naive recursion first, then add a cache — you'll get 80% of the credit.
- Monotonic Stack — Use for "next greater element" and histogram/area style problems. Classic problems: Daily Temperatures, Largest Rectangle in Histogram, Trapping Rain Water. Maintain a stack of indices where values are either strictly increasing or decreasing. This pattern trips up even experienced engineers who've never explicitly learned it.
- Heap / Priority Queue — Use for "top K" problems, merge K sorted lists, or anything requiring repeated extraction of the minimum or maximum efficiently. Classic problems: Kth Largest Element, Merge K Sorted Lists, Task Scheduler. In Java use
PriorityQueue, Python hasheapq.
- Union-Find (Disjoint Set Union) — Use for connectivity problems in undirected graphs, especially when you need to dynamically merge components. Classic problems: Number of Connected Components, Redundant Connection, Accounts Merge. Implement with path compression and union by rank — both are necessary for the O(α(n)) amortized complexity interviewers expect.
- Trie (Prefix Tree) — Use for prefix-matching, autocomplete, and word search problems. Classic problems: Implement Trie, Word Search II, Replace Words. A Trie node has a dictionary of children and an
is_endflag. Know how to build and traverse one from scratch in under 10 minutes.
- Topological Sort — Use for dependency ordering in directed acyclic graphs. Classic problems: Course Schedule, Alien Dictionary, Task Ordering. Two implementations: Kahn's algorithm (BFS-based, using in-degree counts) and DFS-based. Kahn's is easier to reason about in an interview.
- Tree DP / Path Problems — Use for tree problems that ask for max/min path sums, diameters, or require aggregating results from children. Classic problems: Binary Tree Maximum Path Sum, Diameter of Binary Tree. The trick is recognizing that DFS returns a value to its parent while maintaining a global maximum as a side effect.
- Graph Coloring / Bipartite Check — Use for problems that reduce to 2-coloring a graph: scheduling, conflict detection, or even some DP problems on grids. Classic problems: Is Graph Bipartite, Possible Bipartition. BFS or DFS with alternating colors — if you ever try to assign the same color twice, the answer is false.
How to Actually Memorize These Without Flashcards
Don't use flashcards. The research on spaced repetition for code templates is mixed at best, and you don't have unlimited time. Instead, use deliberate problem sets.
- Pick one pattern per day during your active prep sprint.
- Solve 3 easy problems using only that pattern to build muscle memory.
- Solve 2 medium problems where the pattern is slightly disguised.
- Write the template from scratch in your preferred language before bed — no looking it up.
After a two-week sprint following this structure, you will have covered all 15 patterns twice. That's more durable than grinding 150 random problems over two months.
The specific problems that best illustrate each pattern:
- Two Pointers: 167, 15, 11
- Sliding Window: 3, 76, 424
- Monotonic Stack: 739, 84, 42
- Binary Search on Answer: 875, 1011, 410
- Backtracking: 46, 78, 39, 51
These 15 problems alone will tune your eye faster than anything else.
Salary Context: Why This Prep Actually Pays Off in 2026
Let's be direct about the ROI here. In 2026, total compensation for senior engineers at top tech companies in the US ranges from $280K–$420K USD (base + RSUs + bonus at L5/L6 equivalents). The difference between passing and failing a coding screen at that level is not intelligence — it's preparation quality.
For Canadian engineers targeting US remote roles or cross-border opportunities, the gap is even more stark: a senior role at a Canadian company might pay $160K–$220K CAD, while a remote-eligible US tech role at the same level could pay $300K+ USD. The LeetCode screen is the same either way. The return on 40 hours of focused pattern practice, calibrated against that salary delta, is extraordinary.
Principal and Staff-level candidates aren't exempt either. Google L6, Amazon P6, and Meta E6 loops still include 2-3 coding rounds. Solving mediums cleanly and efficiently is a floor requirement — failing one round for a solvable reason is a common single point of failure that tanks otherwise strong loops.
The Patterns You're Most Likely to Waste Time On
Honest advice: not all 15 patterns are equally important for your target companies. Here's where to calibrate:
- Skip deep graph theory (Bellman-Ford, Floyd-Warshall) unless you're targeting companies with heavy infrastructure or routing problems. These appear rarely in product-engineering interviews.
- Don't over-invest in segment trees and Fenwick trees. They're fascinating data structures. They appear in maybe 2% of interviews. If you're pressed for time, defer.
- Don't skip monotonic stack because it sounds obscure. It shows up disproportionately in Amazon and Google mediums and almost everyone except specialists gets it wrong without explicit practice.
- DP deserves more time than you've given it. Most engineers under-prepare DP because it's uncomfortable. The 2D DP problems (LCS, edit distance, grid paths) are a consistent signal-separator at senior levels.
Mock Interviews Beat Solo Practice — But Only If You Do Them Right
After you've internalized the patterns, you need to simulate interview conditions. Solo practice on LeetCode builds pattern recall. Mock interviews build communication, time management, and the ability to think out loud coherently — which is what actually gets you hired.
The rules for effective mock interviews:
- Always use a shared coding environment (Google Docs, Coderpad, or a whiteboard), never your IDE.
- Talk through pattern recognition out loud before you write a single line of code.
- Time yourself: 5 minutes problem comprehension, 5 minutes approach alignment with interviewer, 15 minutes coding, 5 minutes testing and edge cases.
- Debrief after every mock: which pattern did you reach for, was it right, what slowed you down?
- Do at minimum 6 mocks before your first real interview — 2 easy/medium, 2 medium/hard, 2 full loops with behavioral included.
For finding mock partners in 2026: Pramp and Interviewing.io still operate, and peer swaps through company-specific Discord servers have become more common and often higher quality because you're matched with people targeting the same role level.
One Meta-Principle That Changes How You Approach Every Problem
Before you wrap up your prep, internalize this: constraints are hints, not just limits.
- Input array is sorted? Binary search or two pointers.
- Input is a tree or graph? BFS, DFS, or topological sort.
- Problem asks for "top K"? Heap.
- You need to find all combinations/subsets? Backtracking.
- Problem involves a substring or subarray with a constraint? Sliding window.
- You see overlapping decisions? DP.
Interviewers at top companies design problems so that the constraints point clearly to the intended approach — if you know the vocabulary. A well-prepared candidate reads n ≤ 10⁵ and immediately eliminates O(n²). They read "minimum path" and reach for BFS. This is the real cheatsheet: train yourself to read constraint tables like a senior engineer reads logs.
Next Steps
Here's what to do in the next seven days:
- Audit your weak patterns today. Open LeetCode, filter by tag, pick the three patterns you've avoided most (probably DP, monotonic stack, and union-find), and solve one easy problem from each tag without looking at solutions.
- Build your personal template library. Create a private GitHub repo or Notion page. Write each of the 15 templates from scratch in your primary interview language. This is your reference document — update it as you learn edge cases.
- Schedule two mock interviews this week. Reach out to a peer, use Interviewing.io, or find a Discord server for your target companies. Do not wait until you feel "ready" — the discomfort is the point.
- Do a timed 75-minute session on binary search on answer problems (LeetCode 875, 1011, 410). This single pattern is under-studied relative to its interview frequency and will feel like a cheat code once you have it locked.
- Time your pattern recognition. For the next 20 problems you attempt, set a timer and force yourself to classify the pattern within 90 seconds of reading the problem — before you touch the keyboard. Track accuracy. If you're below 70%, revisit the constraint-to-pattern mapping above until it's automatic.
Related guides
- 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.
- DFS LeetCode Pattern Guide — Recursion Templates and Grid/Graph Problems — A DFS LeetCode pattern guide with recursion templates, visited-set rules, grid and graph examples, backtracking structure, complexity notes, and interview pitfalls.
- 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.
