“Return all subsets.” “All permutations.” “Every way to place N queens.” When a question wants every answer, you need backtracking: build answers one choice at a time, and undo each choice to try the next. It's recursion (Part 3) with one extra step.
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stacknext greater element
- 8Heap / Top-Ktop K, Kth largest
- 9Tree Patternsdepth, paths, levels
- 10Grid BFS & Topological Sortislands, dependencies
- 11Backtrackingall combinations
- 12DP Patternscount ways, min cost
The maze story
Exploring a maze: at every fork you pick a path. If it hits a dead end, you walk back to the last fork and try the next path. You never start again from the entrance; you just undo the last choice. That “walk back” is the backtrack. Now build every combo meal from three items:
🍽️ Every possible combo meal, by backtracking
Current tray (the path)
Saved combos (0 / 8)
Three items: pizza, fries, cola. For each, we choose it or skip it. Press Next to explore.
For each item there are 2 choices (take or skip), so 3 items give 2 × 2 × 2 = 8 combos. The “un-choose” step is what makes it backtracking: undo your last choice, then try the other branch, reusing the same path list.
Pruning: don't walk down dead ends
Exploring every branch is slow (2ⁿ subsets, n! arrangements). Pruning stops early when a branch can't work: in N-Queens, never place a queen on an attacked square; in Combination Sum, stop when the total is already too big. Same template, one extra if, often a huge speed-up.
🔍 Use backtracking when you see
- ✓“All subsets / combinations / permutations”
- ✓“Every way to…”, “generate all…”
- ✓Puzzles: N-Queens, Sudoku, word search
- ✓Small inputs (n ≤ 15 or so): exponential is OK
🚫 Don't use it when
- ✗Only a count, minimum or maximum is needed (try DP)
- ✗Large inputs where 2ⁿ is impossible
- ✗A single best pair or window (two pointers, sliding window)
The template
def explore(path, choices):
if path is complete:
results.append(path.copy()) # save a COPY
return
for choice in choices:
if not allowed(choice): continue # prune
path.append(choice) # 1. choose
explore(path, remaining) # 2. explore
path.pop() # 3. un-choose⚡ Memory tricks
- 1
“Choose, explore, un-choose”
The three lines that make every backtracking solution.
- 2
“Save a copy, not the list”
The path keeps changing; copy it when you save.
- 3
“All of them → backtrack. How many / best → DP.”
Lists of answers vs counts and optimums.
- 4
“Prune early, prune often”
Skip choices that can't lead to a valid answer.
Code: subsets and permutations
Outputs in the comments come from running the code.
def subsets(nums):
"""Every choice: take the number, or skip it."""
result, path = [], []
def explore(i):
if i == len(nums):
result.append(path[:]) # one complete set of choices
return
path.append(nums[i]) # choose
explore(i + 1) # explore
path.pop() # un-choose
explore(i + 1) # skip it
explore(0)
return result
def permutations(nums):
"""Fill one seat at a time with a number not used yet."""
result, path, used = [], [], [False] * len(nums)
def explore():
if len(path) == len(nums):
result.append(path[:])
return
for i, x in enumerate(nums):
if not used[i]:
used[i] = True; path.append(x) # choose
explore() # explore
path.pop(); used[i] = False # un-choose
explore()
return result
print(subsets([1, 2, 3])) # [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
print(len(permutations([1, 2, 3])), permutations([1, 2, 3])[:2]) # 6 [[1, 2, 3], [1, 3, 2]]One pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| Subsets | Take or skip each item | Medium |
| Permutations | Fill one seat at a time with unused items | Medium |
| Combination Sum | Reuse allowed; prune when the sum is too big | Medium |
| Letter Combinations of a Phone Number | One digit per level | Medium |
| Generate Parentheses | Add ( or ) while the string stays valid | Medium |
| Word Search | DFS on a grid, mark and un-mark cells | Medium |
| N-Queens | One queen per row, prune attacked columns and diagonals | Hard |
🎯 Spot the pattern: is it backtracking?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Return all combinations of numbers that add up to a target (each can be reused).
2. Place N queens on an N×N board so none attack each other.
3. Count the number of ways to climb n stairs taking 1 or 2 steps.
4. Check whether a word exists in a grid of letters by moving to neighbours.
5. Find the kth largest element.
🧠 PATH memory card
Remember backtracking for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
In a maze you pick a path at each fork; at a dead end you step back to the last fork and try the next path.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Maze: choose a path, explore, step back, try the next”
- Choose a path→path.append(choice)
- Explore→Recurse on what's left
- Step back→path.pop(): un-choose (the backtrack)
- Exit found→Path complete → save a copy
- Blocked corridor→Prune: skip choices that can't work
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Subsets of[1, 2, 3]: take 1 → take 2 → take 3 → save [1,2,3] · un-choose 3, skip → save [1,2] · back up, skip 2 → [1,3], [1] · skip 1 → [2,3], [2], [3], []. 8 subsets. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 6 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Saving the path itself. Save
path.copy()(ornew ArrayList<>(path)). - Forgetting to un-choose. Without
pop(), choices leak into other branches. - Duplicates. With repeated numbers, sort first and skip equal neighbours at the same level.
Where to go next
Backtracking lists every answer. When the question only wants the best or how many, many branches repeat the same work, and you can remember it instead: dynamic programming patterns.
Key takeaways
- ✓Backtracking builds every answer one choice at a time.
- ✓Choose, explore, un-choose; save a copy when the path is complete.
- ✓Subsets: 2ⁿ; permutations: n!; so inputs must be small.
- ✓Pruning skips branches that can't work, often a big speed-up.
- ✓All answers → backtracking; count or best → dynamic programming.
Frequently asked questions
What is backtracking in simple words?
Backtracking builds answers one choice at a time. After each choice it explores further; if that leads to a full answer, it saves it; then it undoes the choice (backtracks) and tries the next option. It's how you generate all subsets, permutations and combinations, or solve puzzles like N-Queens and Sudoku.
What is the backtracking template?
A recursive function with a path: if the path is complete, save a copy. Otherwise, for each allowed choice: add it to the path (choose), recurse (explore), then remove it (un-choose). Pruning means skipping choices that can't possibly work.
What's the difference between backtracking and recursion?
Backtracking is a use of recursion. Plain recursion solves smaller copies of a problem; backtracking specifically explores a tree of choices and undoes each choice after exploring it.
Why is backtracking so slow, and how does pruning help?
The number of answers is huge: 2ⁿ subsets, n! permutations. Pruning cuts branches early when they can't lead to a valid answer (a queen already attacked, a sum already too big), which can save enormous amounts of work in practice.
Backtracking or dynamic programming?
If the question asks for ALL the solutions (list every combination), use backtracking. If it asks for a COUNT, a minimum or a maximum, the overlapping subproblems usually make dynamic programming much faster.
🧠 Quick check: backtracking
1. What are the three steps inside the backtracking loop?
2. How many subsets does a set of 4 items have?
3. “Return all possible arrangements of [1, 2, 3].” Which pattern?
4. Why do we save a COPY of the path, not the path itself?
Checking your access…