Backtracking
Build a candidate one choice at a time, recurse, then undo the choice, abandoning any partial candidate that can't lead to a valid answer: the way to enumerate subsets, permutations and constraint puzzles.
Analogy: Walking a maze with chalk: at each fork take a path, and at a dead end walk back to the last fork and try the next one.
How it works
- Depth-first search over decisions: each level adds one choice to a partial candidate.
- Template: choose, explore, unchoose; save a copy of
pathwhen it is complete. - Pruning rejects a partial candidate early and cuts its whole subtree.
- Cost follows the tree: 2ⁿ subsets, n! permutations, C(n, k) combinations.
- A
startindex for combinations, ausedarray for permutations; sort to skip duplicates.
Check yourself
Answer to mark it learned; your answers aren't scored.
Return every subset of 30 distinct positive numbers whose sum equals a target. Enumerating all subsets and then filtering times out. Best improvement?
Go deeper
Solve it in Python 10
- Every subseteasy
- Words a phone keypad can spelleasy
- Balanced brackets up to a depthmedium
- Deal numbers into k equal pilesmedium
- Every distinct orderingmedium
- Every way to cut into palindromesmedium
- Reach a target, each item oncemedium
- Reach a target, reuse allowedmedium
- Every way to split text into wordshard
- Queens that never attackhard
Full explanation
Backtracking is depth-first search over a tree of decisions. Each node is a partial candidate; each edge adds one choice. The template never changes:
- Choose: add an option to
path. - Explore: recurse on what remains.
- Unchoose: remove it, so the next sibling starts clean.
When path is complete, record a copy of it. Pruning makes it practical: reject a partial candidate the moment it breaks a constraint (a queen under attack, a sum over target) and its whole subtree disappears.
The tree's shape sets the cost: 2ⁿ leaves for subsets, n! for permutations, C(n, k) for combinations. Shape it with a start index (combinations, no reuse), a used array (permutations), or sorting plus skipping equal neighbors (duplicate inputs).
Signals: "all", "every", "generate", "place", with small n (rule of thumb: n ≤ ~20 for subsets, ~10 for permutations). If only a count or an optimum is asked and states repeat, use Dynamic Programming.
Code Subsets and N-Queens with pruning
def subsets(nums): # 2^n results
res, path = [], []
def bt(start):
res.append(path[:]) # copy: path keeps changing
for i in range(start, len(nums)):
path.append(nums[i]) # choose
bt(i + 1) # explore; i + 1 = no reuse
path.pop() # unchoose
bt(0)
return res
def n_queens(n): # count placements, one queen per row
cols, diag, anti = set(), set(), set()
def bt(r):
if r == n:
return 1
total = 0
for c in range(n):
if c in cols or r - c in diag or r + c in anti:
continue # prune: square is attacked
cols.add(c); diag.add(r - c); anti.add(r + c)
total += bt(r + 1)
cols.remove(c); diag.remove(r - c); anti.remove(r + c)
return total
return bt(0)Real example
N-Queens. Place n queens on an n×n board so none attack each other; count the placements. Put one queen per row, so rows never clash. Track attacked columns and both diagonals in sets (r - c and r + c are constant along a diagonal), so the safety check is O(1). Attacked squares are pruned before recursing. For n = 8 the code above finds all 92 solutions in 2,057 calls, versus 8⁸ ≈ 16.7M blind row-by-row placements.
Trade-offs +3 · −3
+ You gain
- One template covers subsets, permutations, combinations and constraint puzzles.
- Memory is O(depth) beyond the output: only the current path is held.
- Pruning can cut the search by orders of magnitude without changing the result.
− You pay
- Exponential or factorial worst case; only viable for small n.
- Easy to leak state: one missed undo corrupts every later branch.
- No reuse across branches; repeated states call for DP instead.
Use it when
You must generate or search every valid configuration (subsets, orderings, placements, grid word paths), n is small, and constraints can reject partial candidates early.
Avoid it when
Only a count or an optimum is asked and subproblems repeat (use DP), or n is large enough that 2ⁿ or n! is out of reach.
Numbers to know 5
- Subsets: 2ⁿ results, O(n·2ⁿ) with copying; n = 20 → 1,048,576 subsets.
- Permutations: n! results; 10! = 3,628,800.
- Combinations: C(n, k) = n! / (k!(n − k)!) results.
- N-Queens: 92 solutions for n = 8 (12 up to rotation and reflection).
- Recursion depth = number of decisions (≤ n), not the number of results.
Common pitfalls 4
- Appending
pathinstead ofpath[:]: every result is the same list, usually empty at the end. - Missing an undo (
pop,used[i] = False), so state leaks into the next sibling. - Duplicate results from repeated inputs: sort, then skip
nums[i] == nums[i-1]wheni > start. - Checking constraints only at the leaves: correct, but nothing is pruned and it times out.
Interview questions 2
Answer out loud first, then reveal.
How do you recognize backtracking, and how is it different from DP?Show answer
Backtracking fits when I must list every valid configuration, or when constraints let me reject partial answers early. DP fits when I need a count or an optimum and the same subproblem recurs. If the prompt says "return all...", the output is already exponential, so backtracking is the right shape. If it says "how many" and states repeat, I memoize instead of enumerating.
How do you handle duplicates, and which variants come up?Show answer
With duplicate inputs I sort, then skip nums[i] == nums[i-1] when i > start, so each value opens a branch once per level. Variants only change the loop: combinations recurse with i + 1 (no reuse); combination sum recurses with i (reuse) and stops once the sum passes the target; permutations use a used array; grid word search marks a cell, tries four neighbors, then unmarks it.