DSA
Master Backtracking Patterns: 7 templates for Coding Interviews
Master 7 backtracking patterns techniques used in Google, Amazon, and Meta interviews.
You've spent hours solving LeetCode problems. You remember painstakingly tracing every possible combination for that "Combination Sum" question, only to realize your code was a tangled mess of nested loops. Then, in your Amazon interview, the interviewer tweaks a single constraint—and suddenly, you're back at square one, staring at a blank screen.
Sound familiar? You're not alone. Most engineers approach these problems by brute-forcing every possibility or memorizing one-off solutions. But when faced with a twist—like duplicate numbers, extra constraints, or grid movement—they freeze. The pattern is there; spotting it is the real challenge.
Here's the truth: Interview success isn't about memorizing 500 solutions—it's about recognizing patterns. Backtracking is one of the most powerful (and misunderstood) patterns in the FAANG interview arsenal, surfacing in nearly 20% of Google's algorithm interviews. Mastering its seven core sub-patterns will transform your approach, turning panic into confident problem-solving.
What You'll Learn
By the end of this guide, you'll master:
✅ The 7 backtracking sub-patterns—from Combination Sum to Word Search
✅ Pattern recognition skills to spot backtracking in any interview question
✅ 19 curated, FAANG-level practice problems (with company tags and star picks)
✅ When to use each backtracking pattern (and how to avoid brute force)
✅ Common pitfalls—and how to sidestep them like a pro
✅ A practical, 2-3 week practice roadmap from basics to mastery
What is Backtracking Patterns?
Imagine you're in a massive maze. At every intersection, you make a choice: left, right, or straight. If you hit a dead end, do you give up? Of course not! You backtrack—you retrace your steps to the last decision point and try a different path. That's the essence of backtracking: a smart, systematic way to explore all possible solutions, undoing choices as soon as you know they won't work.
The core insight: Backtracking is recursive trial-and-error with pruning. Rather than exhaustively generating every possibility, you build solutions step by step, abandoning ("backtracking") as soon as you detect a dead end. It's smarter than brute force, but more flexible than greedy algorithms.
Why This Pattern Matters
- Solves "All Combinations/Arrangements" Problems: Many FAANG interview questions—like N-Queens or Palindrome Partitioning—require exploring all valid configurations.
- Enables Efficient Pruning: Backtracking stops exploring paths as soon as they're invalid, making it dramatically faster than unchecked brute force.
- Highly Transferable: Mastering the pattern helps with recursion, dynamic programming, and constraint satisfaction.
- Tests Real Problem-Solving: Interviewers use backtracking to see if you can break down complex, combinatorial problems and optimize your code.
Companies that frequently ask backtracking questions: Google, Amazon, Meta (Facebook), Microsoft, Apple, Uber, ByteDance, Bloomberg, Airbnb, DoorDash, Oracle, Pinterest.
The 7 Backtracking Patterns Sub-Patterns
Let's break down the seven essential backtracking sub-patterns every FAANG candidate must know. For each, you'll learn the mental model, recognition triggers, must-practice problems, and a code template.
1. Combination Sum
What it is:
Combination Sum problems ask you to find all unique combinations from a set of numbers that add up to a specific target—without caring about order. Think of choosing coins to make a certain amount, or selecting menu items to match a calorie count.
Key insight:
The core of Combination Sum is recursive exploration with pruning. At each step, you can choose to include a number (sometimes multiple times), and you explore only paths that haven't exceeded the target. The magic is in pruning paths early—if your current sum > target, backtrack immediately.
How it works:
- Sort (if necessary): Helps with duplicate management and early pruning.
- Recursive function: At each index, choose to include or skip the current number.
- Terminate when:
- The running sum equals the target (valid combination—add to result).
- The running sum exceeds the target (invalid—backtrack).
- Backtrack: Remove the last number before trying the next candidate.
When to use:
- You need all combinations (not just one) that sum to a target.
- Order of numbers in combinations doesn't matter.
- Duplicate numbers may or may not be allowed (read the problem carefully!).
- You're allowed to reuse numbers (check problem statement).
Recognition triggers:
- "Find all combinations that sum to target"
- "Return all unique combinations" (order doesn't matter)
- "Each number may be used multiple times" or "use each only once" (see Combination Sum II)
Essential Problems:
Medium:
- ⭐ Combination Sum - Facebook, Airbnb, Microsoft, Bloomberg, Amazon
Classic: Find all combinations (reuse allowed). - ⭐ Combination Sum II - Amazon, Uber, Microsoft, ByteDance
Each number may be used once; input may contain duplicates.
💡 Pro Tip:
Always sort your array first—this enables early pruning and makes it easier to skip duplicates (especially in Combination Sum II).
⚠️ Common Mistake:
Forgetting to skip duplicates. In problems like Combination Sum II, failing to skip over repeated numbers at the same recursion depth will yield duplicate combinations. Always check if candidates[i] == candidates[i-1] at the same depth and skip accordingly.
Example Code Pattern:
PYTHON
Time/Space Complexity:
- Time: O(2^n) in the worst case (all combinations)
- Space: O(target/ min(candidate)) for recursion stack and result storage
2. N-Queens / Constraint Satisfaction
What it is:
N-Queens and constraint satisfaction problems require placing entities (like queens, numbers, or tiles) onto a board/grid so that a set of constraints are satisfied. It's all about finding valid configurations under strict rules.
Key insight:
The heart of this pattern is early pruning by checking constraints at each step. By only placing a queen (or number) if it doesn't violate any constraints, we avoid exploring doomed branches. The more efficiently you can check constraints, the faster your backtracking will be.
How it works:
- Choose a position: Place a queen/number at the current row/column.
- Check constraints: Is this position valid? (e.g., not in the same row/col/diagonal for N-Queens)
- Recurse: Move to the next row/column/cell.
- Backtrack: Remove the entity and try the next position.
When to use:
- You need to fill a grid/board under fixed rules (e.g., Sudoku, N-Queens).
- The problem mentions "place X objects so that...".
- The task involves preventing conflicts or overlaps.
- Checking the validity of every move is possible in O(1).
Recognition triggers:
- "Place X so that no two... conflict"
- "Fill the grid so that..." (with rules)
- "Find all valid arrangements/solutions"
Essential Problems:
Hard:
- ⭐ N-Queens - Facebook, Microsoft, Amazon, ByteDance, Apple
Classic: Place N queens on an N×N chessboard so no two attack each other. - ⭐ Sudoku Solver - DoorDash, Amazon, Oracle, Pinterest, Facebook
Fill a 9x9 Sudoku grid; constraints on rows, columns, and boxes.
💡 Pro Tip:
Precompute constraint checks using sets or bitmasks for O(1) validity checking. For N-Queens, use sets to track columns and diagonals; for Sudoku, use 3 sets (rows, columns, boxes).
⚠️ Common Mistake:
Not undoing state changes when backtracking. Always "unset" your choice (e.g., remove from sets) after recursion returns, or you'll carry invalid state into subsequent branches.
Example Code Pattern:
PYTHON
Time/Space Complexity:
- Time: O(N!) for N-Queens
- Space: O(N^2) for the board, plus recursion stack
3. Palindrome Partitioning
What it is:
Palindrome Partitioning explores all ways to split a string into substrings where every substring is a palindrome. It's a classic "partition and validate" scenario, often used to test deep recursion and string manipulation.
Key insight:
The secret sauce here is partitioning at every possible position and only proceeding with the recursion if the current substring is a palindrome. By checking for palindromes early, you prune branches that can't lead to a valid solution.
How it works:
- Start at index 0.
- For every end index > start, check if
s[start:end]is a palindrome. - If yes, add to current path and recurse from
end. - If you reach the end of the string, add the current partition to the results.
- Backtrack: remove the last substring and try the next partition.
When to use:
- You need to split a string into all valid palindromic substrings.
- The problem asks for the minimum or all ways to partition.
- There's a need to check substring properties recursively.
Recognition triggers:
- "Partition string into palindromes"
- "Find all/many possible partitions"
- "Minimum cuts for palindrome partitioning"
Essential Problems:
Medium:
- ⭐ Palindrome Partitioning - Amazon, Apple, Google
Partition a string so every substring is a palindrome. - Pseudo-Palindromic Paths in a Binary Tree - Amazon
Paths in a tree that can be permuted to a palindrome.
Hard:
- Palindrome Partitioning II - Amazon, Google
Min cuts for palindrome partitions.
💡 Pro Tip:
Precompute palindrome substrings using dynamic programming or memoization to avoid redundant checks, especially for large strings.
⚠️ Common Mistake:
Checking for palindromes inefficiently (O(n) per check). Use a helper function to check palindromes, or precompute a DP palindrome table for O(1) lookup.
Example Code Pattern:
PYTHON
Time/Space Complexity:
- Time: O(2^n * n) (all possible partitions, each check is O(n))
- Space: O(n) (recursion stack), plus result storage
4. Parentheses Generation
What it is:
This pattern generates all valid strings of balanced parentheses (or similar paired structures). It's a canonical example of constrained generation—producing combinations that obey rules at every step.
Key insight:
The trick is to track counts of open and close brackets. At each step, you can add an open bracket if you haven't used them all, or a close bracket if it won't unbalance the string. This ensures only valid sequences are created—no need for post-generation validation.
How it works:
- Start with an empty string and two counters: open and close.
- If open < n, add '('. If close < open, add ')'.
- When both counters reach n, add to the result.
- Recursively build up valid strings.
When to use:
- Generate all valid parentheses/bracket/brace combinations.
- Problems involving "well-formed" or "balanced" symbols.
- Need to generate combinations under pairwise constraints.
Recognition triggers:
- "Generate all combinations of balanced parentheses"
- "Return all valid strings of length 2n"
- "Remove minimum invalid parentheses"
Essential Problems:
Medium:
- ⭐ Generate Parentheses - Microsoft, Facebook, Google, Bloomberg, Amazon
Generate all well-formed parentheses for n pairs.
Hard:
- Remove Invalid Parentheses - Facebook, Bloomberg, ByteDance, Amazon, Qualtrics
Remove minimum invalid parentheses to make string valid.
💡 Pro Tip:
Prune early: Only add a close parenthesis if it won't unbalance the string (i.e., close < open). This avoids generating invalid strings.
⚠️ Common Mistake:
Forgetting to check the close < open constraint. This leads to unbalanced or invalid strings, wasting time on dead-end branches.
Example Code Pattern:
PYTHON
Time/Space Complexity:
- Time: O(2^n) (Catalan number)
- Space: O(n) for recursion stack
5. Permutations
What it is:
Permutations problems ask for all possible orderings of a set of items. Unlike combinations, order matters. This pattern is a staple in interviews involving arrangements or sequences.
Key insight:
The critical move here is to swap or mark used elements at each recursion level to avoid repeats. By tracking which elements are used, you prevent generating duplicate permutations and ensure all orderings are explored.
How it works:
- For each position in the permutation, try all unused elements.
- Mark an element as used, recurse to the next position.
- After recursion, unmark (backtrack) and try the next unused element.
When to use:
- Need all orderings/arrangements of items.
- The problem asks for permutations, sequences, or "next/previous permutation".
- Elements must not repeat in the same arrangement.
Recognition triggers:
- "Return all possible permutations"
- "Find the next permutation in lex order"
- "Arrange elements in all possible ways"
Essential Problems:
Medium:
- ⭐ Permutations - Facebook, Amazon, ByteDance, LinkedIn, Apple
All possible orderings of a list. - ⭐ Next Permutation - Facebook, Amazon, Google, Microsoft, Rubrik
Find next lexicographical permutation.
Hard:
- Permutation Sequence - Amazon, Adobe
k-th permutation sequence in lex order.
💡 Pro Tip:
Use in-place swapping (for arrays) or a used boolean list (for lists) to optimize memory and avoid unnecessary copies.
⚠️ Common Mistake:
Reusing the same element more than once per permutation. Always track which elements you've used at the current recursion depth.
Example Code Pattern:
PYTHON
Time/Space Complexity:
- Time: O(n!)
- Space: O(n) recursion depth, plus O(n!) for results
6. Subsets (Include/Exclude)
What it is:
The Subsets pattern explores all possible subsets (the power set) of a set. At each step, you choose to include or exclude the current element, resulting in 2^n possible subsets.
Key insight:
This is the "binary decision tree" of backtracking: each element is a fork—include or skip. By traversing every decision, you generate all subsets systematically.
How it works:
- Start with an empty path.
- At each index, recursively:
- Include the current element and move forward.
- Exclude the current element and move forward.
- Add the path to results at each step.
When to use:
- You need all subsets (power set), or all combinations of k elements.
- "Pick or skip" scenarios.
- Mapping to binary choices per element.
Recognition triggers:
- "Return all subsets/combinations"
- "Generate the power set"
- "Pick any subset of elements"
Essential Problems:
Medium:
- ⭐ Subsets - Facebook, Bloomberg, Amazon, Uber, Microsoft
All possible subsets of a list. - ⭐ Combinations - Facebook, Amazon
All combinations of k elements from n. - ⭐ Letter Combinations of a Phone Number - Amazon, Microsoft, Twilio, Facebook, Capital One
Map digits to letter combinations (phone keypad). - Subsets II - Amazon, ByteDance
Subsets with possible duplicates.
💡 Pro Tip:
Add the current path to results at every node—not just leaves. This neatly captures all subsets, including the empty set.
⚠️ Common Mistake:
Missing subsets by only adding paths at the leaves. To get all subsets, add path[:] to your result at every recursion step (before deeper calls).
Example Code Pattern:
PYTHON
Time/Space Complexity:
- Time: O(2^n)
- Space: O(n) recursion stack, plus O(2^n * n) for results
7. Word Search / Path Finding in Grid
What it is:
This pattern explores all possible paths or words in a 2D grid, moving in allowed directions (typically up/down/left/right), sometimes with constraints like "each cell can be used only once".
Key insight:
The main technique is backtracking with in-place marking. As you traverse the grid, you mark cells as visited, and backtrack (unmark) as you return. Early pruning is critical—if the next character/cell doesn't match, backtrack immediately.
How it works:
- For each starting cell, run a DFS to find the path/word.
- At each step, mark the cell as visited (commonly by modifying the board or keeping a visited set).
- Explore all valid neighbors (up/down/left/right).
- If the full word/path is matched, return True/add to results.
- On backtrack, unmark the cell as visited.
When to use:
- Search for a word/path in a 2D board/grid.
- Movement is constrained (e.g., no revisiting cells).
- Need to find all or any valid paths.
Recognition triggers:
- "Find all words in a board/grid"
- "Can you reach target/exit/cell?"
- "Path-finding with constraints"
Essential Problems:
Medium:
- Check if Word Can Be Placed In Crossword
Can the word fit in a crossword grid? - ⭐ Word Search - Amazon, Bloomberg, Intuit, Microsoft, Facebook
Is the word present in the grid?
Hard:
- Word Search II - Amazon, Microsoft, Uber, Apple, Google
Find all words from a list in a grid.
💡 Pro Tip:
Modify the board in place (e.g., set to '#') to mark as visited, then restore on backtrack. This saves space and avoids extra data structures.
⚠️ Common Mistake:
Forgetting to restore the cell after recursion. This causes cells to be incorrectly marked as visited in later paths, leading to wrong answers.
Example Code Pattern:
PYTHON
Time/Space Complexity:
- Time: O(m * n * 4^L), where L = word length
- Space: O(L) recursion depth
How to Master Backtracking Patterns on Thita.ai
Ready to transform your backtracking skills from "I sort of get it..." to "Bring on the FAANG interview"? Thita.ai gives you everything you need:
- Pattern-Based Problem Sets:
Practice all 19 backtracking problems in our DSA Patterns Sheet, sorted by sub-pattern and difficulty. - AI Hints & Instant Feedback:
Stuck on a problem? Get contextual hints and see test case feedback instantly in Code Practice. - Real Interview Simulation:
Test your speed and pattern recognition with our AI Interview Simulator. - Track Your Progress:
Visualize your mastery by sub-pattern and difficulty in your Personal Dashboard. - Technical Coaching:
Get personalized feedback and mock interview coaching from our AI Coach.
Your Backtracking Patterns Learning Roadmap
Invest 2-3 weeks, and you'll be unstoppable in interviews.
Week 1: Foundations (Days 1-4, ~1-1.5 hrs/day)
- Day 1:
- Subsets ⭐
- Combinations ⭐
- Focus: Learn binary include/exclude; visualize recursion tree.
- Day 2:
- Generate Parentheses ⭐
- Letter Combinations of a Phone Number ⭐
- Focus: Pairwise constraints, mapping digits to letters.
- Day 3:
- Permutations ⭐
- Combination Sum ⭐
- Focus: Order vs. selection, handling duplicates.
- Day 4:
- Palindrome Partitioning ⭐
- Word Search ⭐
- Focus: String partitioning, path finding in grids.
Week 2: Intermediate (Days 5-9, ~1.5 hrs/day)
- Day 5-6: Subsets and Combinations Advanced
- Subsets II
- Check if Word Can Be Placed In Crossword
- Focus: Handling duplicates, grid constraints.
- Day 7-8: Constraint Satisfaction & Palindrome Cuts
- Pseudo-Palindromic Paths in a Binary Tree
- Next Permutation ⭐
- Combination Sum II ⭐
- Focus: Binary tree paths, lex order, single-use constraints.
- Day 9: Mixed Practice
- Word Search II
- Remove Invalid Parentheses
- Focus: Multiple words, advanced pruning.
Week 3: Mastery (Days 10-14, ~2 hrs/day)
- Day 10-12: Hard Problems by Subpattern
- Day 13-14: Mixed Practice, Timed Challenges
- Randomly pick problems from all sub-patterns
- Simulate a 1-hour timed session in AI Interview Simulator
- Review with AI Coach for feedback and tips
Estimated Total Time Commitment: 22-30 hours over 3 weeks.
Common Backtracking Patterns Pitfalls
Let's tackle the errors that derail even experienced candidates:
⚠️ 1. Not Pruning Early Enough
Mistake: Continuing down a path even after it's clear it's invalid (e.g., sum exceeds target in Combination Sum).
Solution: Always check constraints before recursing. Add early returns for invalid states:
PYTHON
⚠️ 2. Not Restoring State on Backtrack
Example: In N-Queens, forgetting to remove a queen from the set after recursion.
Bad:
PYTHON
Good:
PYTHON
⚠️ 3. Generating Duplicate Solutions (Combinations/Permutations)
Mistake: Not skipping duplicate elements, especially in Combination Sum II or Subsets II.
Solution: After sorting, skip duplicates at the same recursion level:
PYTHON
⚠️ 4. Not Marking/Unmarking Cells in Grid Problems
Example: In Word Search, failing to restore the cell after recursion.
Solution:
PYTHON
⚠️ 5. Stack Overflow Due to Infinite Recursion
Cause: Not advancing indices or not having a base case.
Solution: Always have well-defined base cases and increment your indices correctly on each recursive call.
⚠️ 6. Wrong Termination Condition
Mistake: Returning result before exploring all branches, or not recognizing when a valid solution is found.
Solution: Double-check your base cases: should you add to results when start == len(nums)? When open == n and close == n?
⚠️ 7. Mixing Up Permutations and Combinations
Mistake: Generating orderings when order doesn't matter, or vice versa.
Solution: Read the problem statement carefully. Use index-based loops for combinations (start from i), and used markers for permutations.
Why Backtracking Patterns Beat Brute Force
Let’s see this in action with Combination Sum.
Brute Force Approach
Try every possible subset, check if sum equals target.
PYTHON
- Complexity: O(2^n * n)
- Problem: Generates all subsets, even those that exceed the target.
Backtracking (Pattern Approach)
Prune branches as soon as the sum exceeds target.
PYTHON
- Complexity: O(2^n), but practical runtime is much faster due to pruning.
Key insight:
Backtracking actively avoids paths that are doomed to fail, while brute force blindly explores every possibility. In large search spaces (e.g., N-Queens, Sudoku), this difference is the only reason these problems are tractable.
When does backtracking shine?
- When the solution space is exponential, but many paths can be ruled out early by constraints.
- When generating all solutions, not just checking for existence.
Beyond LeetCode: Real-World Applications
Backtracking isn't just a "toy" interview pattern—it's used in real production systems:
-
Constraint Solvers (Google, Facebook):
Google Maps' route planning, Facebook's Graph Search, and Google Calendar’s meeting scheduler use backtracking for constraint satisfaction (e.g., time slots, resources, dependencies). -
AI & Game Algorithms (Amazon, Microsoft):
Chess engines, Sudoku solvers, and puzzle games use backtracking to explore possible moves and prune impossible states, providing fast solutions in complex state spaces. -
Compilers & Parsers (Apple, Oracle):
Programming language parsers use backtracking to handle ambiguous grammars and resolve which parsing rule applies, especially in regex engines. -
Network Routing (Cisco, Meta):
Data packet routing in complex networks uses backtracking to identify viable paths under heavy constraints (bandwidth, latency, firewall rules). -
Bioinformatics (23andMe, Google Health):
DNA sequence alignment and motif finding algorithms often rely on backtracking to efficiently search for matching patterns across massive genomes.
Performance Benefits:
Backtracking, with pruning, reduces resource consumption, speeds up search, and allows systems to handle exponential problem spaces in real time.
Conclusion: From Memorization to Mastery
Key takeaways:
- Backtracking is not about brute force—it's about smart exploration and pruning.
- Mastering the 7 sub-patterns unlocks solutions to 20%+ of FAANG interview questions.
- Recognize the triggers: "all combinations", "constraints", "path finding", "arrangements", and so on.
- Avoid the common pitfalls: prune early, restore state, and mark/unmark correctly.
Next steps:
- Start with the DSA Patterns Sheet—work through all backtracking problems, sorted by pattern.
- Practice under time pressure in AI Interview Simulator—simulate the real thing.
- Use Code Practice to get instant feedback and AI-powered hints.
- Review your strengths/weaknesses in your Personal Dashboard and get personalized coaching with AI Coach.
Remember:
In interviews, it's not about memorizing solutions—it's about seeing the pattern hiding in plain sight. Master backtracking, and you'll never be lost in the maze again.