Backtracking builds candidate solutions one choice at a time and abandons a partial candidate as soon as it cannot lead to a valid solution. It is a depth-first search over a tree of decisions: choose, explore, then undo the choice and try the next one. It is the standard tool for generating all subsets, permutations and combinations, and for constraint puzzles such as N-Queens, Sudoku and word search.
Think of it like
Exploring a maze with chalk
At each fork you pick a corridor and mark your path in chalk. If you hit a dead end, you walk back to the last fork, erase the chalk you just drew, and try the next corridor. You never explore the same partial path twice, and you turn around the moment a corridor is clearly hopeless instead of walking to its end.
How it works
Every backtracking algorithm has the same skeleton. The state is the partial solution built so far. At each step you loop over the choices that are still legal, apply one, recurse, and then revert it so the state is clean for the next choice.
def backtrack(state, results):
if is_complete(state):
results.append(snapshot(state)) # copy! the state keeps changing
return
for choice in candidates(state):
if not is_valid(state, choice): # pruning: skip hopeless branches early
continue
apply(state, choice) # choose
backtrack(state, results) # explore
undo(state, choice) # unchoose- State
- The partial solution: the current path, board, or set of chosen items.
- Choice
- One way to extend the state: the next element, the next column, the next digit.
- Constraint
- A rule a valid solution must satisfy; checking it early is what makes backtracking faster than brute force.
- Goal
- The test for a complete solution: depth reached, target sum hit, board full.
- Pruning
- Cutting off an entire subtree because no completion of the current state can succeed.
How to recognize it
- The problem asks for all solutions: "generate all", "list every", "return all possible".
- It asks whether any arrangement satisfies a set of constraints (puzzles, placements, assignments).
- Input sizes are small: n ≤ 10 to 20 for permutations or subsets, a 9 × 9 board, a word of length ≤ 15.
- There is no obvious greedy rule or polynomial DP, often because the underlying problem is NP-hard, see Complexity Classes: P vs NP.
| Constraint on n | Search space you can afford | Typical problem |
|---|---|---|
| n ≤ 8 to 10 | n! ≈ 3.6 million at n = 10 | Permutations, N-Queens |
| n ≤ 20 | 2ⁿ ≈ 1 million | Subsets, partitions |
| n ≤ 40 | 2^(n/2) per half (meet in the middle) | Subset sum on large n |
| Grid ≤ 6 × 6, word ≤ 15 | cells × 3^length with pruning | Word search |
The state-space tree
Picture every partial solution as a node: the root is the empty state, each edge is a choice, and leaves are complete candidates. Backtracking is a depth-first traversal of this tree that refuses to enter subtrees that violate a constraint. The tree is never built in memory; only the current root-to-node path exists at any moment, so memory is O(depth).
Subsets
Two equivalent formulations. Include/exclude: for each element, branch on taking it or not, giving a binary tree of depth n with 2ⁿ leaves. Pick the next element: from position start, choose any later element to add; every node of this tree is a subset, which makes it easy to add constraints like size or sum.
used array) or Combination sum, where sorted candidates let the search break off whole branches.Handling duplicates
With duplicates such as [1, 2, 2], sort first, then at each level skip a value equal to the previous one at that same level: if i > start and nums[i] == nums[i - 1]: continue. This lets the first 2 be chosen at a level but not the second, which would generate the same subsets again.
Permutations
Each level fills one position with any element not yet used, tracked with a used boolean array (or by swapping elements into place). The tree has n! leaves and copying each costs O(n), so generating all permutations is O(n · n!). For duplicates, sort and skip nums[i] == nums[i - 1] when the previous equal element is not currently used.
Combination sum
Find all combinations of candidates that sum to a target, where each candidate may be reused. Two details carry the solution: recurse with the same index i (not i + 1) to allow reuse, and sort the candidates so you can break as soon as a candidate exceeds the remaining target, since every later candidate is larger.
| Path | Remaining | Outcome |
|---|---|---|
[2, 2, 2] | 1 | Next candidate 2 > 1: break, backtrack |
[2, 2, 3] | 0 | Solution |
[2, 3] | 2 | 3 > 2: break |
[3, 3] | 1 | 3 > 1: break |
[6] | 1 | 6 > 1: break |
[7] | 0 | Solution |
[2, 3, 6, 7], target 7: the answer is [[2, 2, 3], [7]].N-Queens
Place n queens on an n × n board so no two attack each other. Place exactly one queen per row; the choice at each level is the column. A square (r, c) is safe if its column, its diagonal r - c and its anti-diagonal r + c are all free. The visualization above places queens row by row, marks attacked squares, and backtracks when a row has no safe column.
| n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| Solutions | 1 | 0 | 0 | 2 | 10 | 4 | 40 | 92 |
Bitmask optimization
For counting solutions, represent the three constraint sets as bitmasks. The free columns in the current row are ~(cols | diag | anti) & full; take the lowest set bit with free & -free; shift the diagonal masks by one when moving to the next row. It is the standard trick for fast N-Queens counting. See Bit Manipulation.
def total_n_queens(n: int) -> int:
full = (1 << n) - 1
def place(cols: int, diag: int, anti: int) -> int:
if cols == full: # a queen in every column: one solution
return 1
count = 0
free = full & ~(cols | diag | anti)
while free:
bit = free & -free # lowest free column
free ^= bit
count += place(cols | bit,
((diag | bit) << 1) & full,
(anti | bit) >> 1)
return count
return place(0, 0, 0)Sudoku
Find an empty cell, try each digit 1 to 9 that is not already in its row, column or 3 × 3 box, recurse, and clear the cell on failure. Keep nine row sets, nine column sets and nine box sets (box index (r / 3) × 3 + c / 3) so each check is O(1).
Word search
Start a DFS from every cell that matches the first letter. At each step, move to one of the four neighbors that matches the next letter. Mark the current cell as visited by overwriting it (for example with #) and restore it when you return. Cost is O(m × n × 3^L): after the first step, each cell has at most three unvisited neighbors.
def exist(board: list[list[str]], word: str) -> bool:
rows, cols = len(board), len(board[0])
def dfs(r: int, c: int, k: int) -> bool:
if k == len(word):
return True
if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[k]:
return False
saved, board[r][c] = board[r][c], "#" # choose: mark visited
found = (dfs(r + 1, c, k + 1) or dfs(r - 1, c, k + 1)
or dfs(r, c + 1, k + 1) or dfs(r, c - 1, k + 1))
board[r][c] = saved # unchoose: restore
return found
return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))Pruning: the difference between fast and hopeless
- Check constraints before recursing, not at the leaves.
- Sort and break: with sorted candidates, the first one that overshoots means all later ones do too.
- Bounding (branch and bound): if even an optimistic estimate of the best completion cannot beat the best solution found so far, stop.
- Symmetry breaking: in N-Queens, place the first queen only in the left half and double the count (handling the middle column for odd n).
- Ordering heuristics: try the most constrained variable first (Sudoku) or the most promising value first.
- Memoization: if the same sub-state recurs, cache it; at that point the search has become DP Fundamentals.
Estimating complexity
| Problem | Branching × depth | Bound |
|---|---|---|
| Subsets | 2 choices × n levels | O(n · 2ⁿ) |
| Permutations | n, n−1, …, 1 | O(n · n!) |
| Combination sum | up to k candidates, depth target / min | Exponential; heavily pruned |
| N-Queens | ≤ n, n−2, … columns per row | O(n!) upper bound |
| Sudoku | ≤ 9 digits per empty cell | O(9^empty), tiny in practice |
| Word search | 4 then 3 neighbors, depth L | O(m · n · 3^L) |
Backtracking vs other strategies
Generate and test
- Build every complete candidate, then check it
- No pruning
- Only viable for tiny inputs
Backtracking
- Check constraints on partial states
- Prunes whole subtrees
- Best when you need all solutions or any valid one
Dynamic programming
- Needs overlapping subproblems
- Counts or optimizes without listing
- Use when only the number or best value is needed
Complexity
| Problem | Time | Space | Notes |
|---|---|---|---|
| Subsets | O(n · 2ⁿ) | O(n) | 2ⁿ subsets, O(n) to copy each |
| Permutations | O(n · n!) | O(n) | Recursion depth and used array |
| Combination sum | O(2^t) | O(t) | Loose bound; t = target / smallest candidate |
| N-Queens | O(n!) | O(n) | Pruning makes it far smaller in practice |
| Sudoku | O(9^m) | O(m) | m = empty cells; constraint sets prune hard |
| Word search | O(m · n · 3^L) | O(L) | L = word length |
Space excludes the output, which can itself be exponential.
Implementation
The two fundamental generators: pick-the-next-element for subsets, a used array for permutations.
def subsets(nums: list[int]) -> list[list[int]]:
res: list[list[int]] = []
path: list[int] = []
def backtrack(start: int) -> None:
res.append(path[:]) # every node is a subset
for i in range(start, len(nums)):
path.append(nums[i]) # choose
backtrack(i + 1) # explore
path.pop() # unchoose
backtrack(0)
return res
def permutations(nums: list[int]) -> list[list[int]]:
res: list[list[int]] = []
path: list[int] = []
used = [False] * len(nums)
def backtrack() -> None:
if len(path) == len(nums):
res.append(path[:])
return
for i, x in enumerate(nums):
if used[i]:
continue
used[i] = True
path.append(x)
backtrack()
path.pop()
used[i] = False
backtrack()
return resKey takeaways
- Backtracking is DFS over a tree of partial solutions: choose, explore, unchoose.
- Pruning partial states early is what separates backtracking from brute-force generate-and-test.
- Subsets cost O(n · 2ⁿ) and permutations O(n · n!); estimate other searches as branching^depth × work per node.
- N-Queens uses one queen per row with O(1) column, diagonal (
r - c) and anti-diagonal (r + c) checks; 8 queens have 92 solutions. - Copy the path when recording a result, and restore every piece of state you modify.
Common pitfalls
- Appending the mutable
pathinstead of a copy, so every stored result ends up empty. - Forgetting to undo a change (a visited mark, a set entry), which silently corrupts sibling branches.
- Recursing with
i + 1when reuse is allowed, or withiwhen it is not. - Generating duplicate results from duplicate inputs because equal values are not skipped at the same level.
- Checking constraints only at the leaves, which throws away all the pruning.
Interview tips
- Describe the decision made at each level and the pruning rule before writing code.
- Give the complexity as branching factor to the power of depth, times the cost of copying a solution.
- Offer optimizations as follow-ups: sorting for early breaks, bitmasks for N-Queens, the most-constrained-cell heuristic for Sudoku.
Real-world applications
- Constraint solvers for puzzles, timetabling and configuration problems.
- SAT solvers (DPLL and CDCL are backtracking with clever pruning and learning).
- Parsing with ambiguous grammars and regular-expression engines with backreferences.
- Exhaustive test-case generation and combinatorial search in games.
Practice problems
Test yourself
Why does a backtracking algorithm undo its choice after the recursive call returns?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.