Backtracking
Build a solution one choice at a time, and undo the dead ends.
There are ways to put 8 queens on a chessboard, and only 92 of them have no two queens attacking each other. A backtracking search finds all 92 after visiting just 2,057 partial boards, because it abandons a board the moment two of its queens clash, and with it every way of finishing that board.
What you’ll learn
- Write the choose–explore–un-choose template and use it to generate subsets, permutations, combinations and combination sums in a predictable order.
- Bound a backtracking search by (nodes visited) × (work per node), and count the nodes of the standard trees: for subsets, for permutations.
- Prune with feasibility tests, prove that a pruning rule never loses a solution, and solve n-queens with sets or bitmasks and sudoku with the most-constrained-cell rule.
- Avoid duplicate solutions by sorting and skipping equal siblings, and break symmetries such as interchangeable empty groups.
- Recognize backtracking problems from their statements and constraints, and tell them apart from look-alikes that need dynamic programming, BFS or a formula.
Choose, explore, un-choose
Many problems ask you to produce every object of some kind (all subsets, all orders, all placements of pieces), or to decide whether any object obeys a set of rules. The brute force generates every complete candidate and tests it. Backtracking builds candidates one choice at a time instead, and tests as it goes.
The partial candidates form a rooted tree, the state-space tree: the root is the empty candidate, each edge is one choice, and each node is the partial candidate spelled out by its path from the root. Backtracking walks this tree depth first and keeps only the current path in memory.
BACKTRACK(p): # p: the partial candidate at the current node
if p is complete:
if p is valid: REPORT(p)
return
for each choice c available at p:
if CAN-SUCCEED(p + c): # prune: skip children that cannot lead to a solution
apply c to p # choose
BACKTRACK(p) # explore
undo c # un-chooseUn-choose restores exactly, so the next sibling starts from the same state as the last one did. Without CAN-SUCCEED this is exhaustive search; with it, whole subtrees vanish unvisited.
def subsets(items):
out, cur = [], []
def go(i): # decide items[i], items[i+1], ...
if i == len(items):
out.append(cur[:]) # a leaf: one complete subset (copy it!)
return
cur.append(items[i]) # choose: include items[i]
go(i + 1) # explore
cur.pop() # un-choose
go(i + 1) # explore the subsets without items[i]
go(0)
return out
print(subsets([1, 2, 3]))
# [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]One shared list cur holds the path from the root to the current node, so out.append(cur[:]) must store a copy: cur keeps changing after the leaf is reported.
The size of the tree is the running time
A backtracking search costs the number of nodes it visits times the work done at each node: checking a constraint, updating the state, and at a solution copying out up to items. So the first question about any backtracking algorithm is how big its tree is.
The shape depends only on how choices are made, not on the code. Each problem below fixes what a level chooses, and that fixes the counts:
| Problem | Choice at depth | Leaves | Nodes | Listing everything |
|---|---|---|---|---|
| Subsets of items | include or exclude item | |||
| Permutations of distinct items | any unused item | |||
| -combinations of items | an item larger than the last one | without the "enough left" test | with the test | |
| Placements of queens, one per row, never checked early | any column | hopeless beyond |
A node at depth is an ordered choice of distinct items out of , so depth holds nodes. Summing over the depths and writing :
The series for is . What the finite sum leaves out is tiny:
So is the integer just below . Only a fraction of the nodes are leaves, and the search does work per leaf to copy a permutation out:
How many nodes, the root included, does the permutation tree of 4 distinct items have?
Show the answer
65
Level by level: , which is . The last level repeats the 24 of the one above it, because once three items are placed the fourth is forced.
Pruning without losing solutions
Pruning tests each partial candidate and abandons it, with its whole subtree, as soon as the test fails. The danger is obvious: a careless test can throw away a subtree that contains a solution. The rule that keeps pruning safe is short.
The easy source of safe tests is a constraint that, once broken, stays broken in every extension: two queens that attack each other still attack each other after more queens arrive, and a sum of positive numbers that has passed the target never comes back down.
For the n-queens puzzle, put one queen in each row, so the choice at depth is the column of row 's queen. Squares on one diagonal share , and squares on one anti-diagonal share . Three sets make every attack test :
def n_queens(n):
cols, diag, anti = set(), set(), set() # columns, r - c and r + c in use
board, solutions = [], []
def place(r):
if r == n:
solutions.append(board[:]); return
for c in range(n):
if c in cols or r - c in diag or r + c in anti:
continue # prune: this square is attacked
cols.add(c); diag.add(r - c); anti.add(r + c); board.append(c)
place(r + 1)
cols.remove(c); diag.remove(r - c); anti.remove(r + c); board.pop()
place(0)
return solutions
print(len(n_queens(8)), n_queens(8)[0]) # 92 [0, 4, 7, 5, 2, 6, 1, 3]For 8 queens this visits 2,057 nodes, the empty board included, against the nodes of the tree that checks only full boards.
#include <cstdio>
unsigned full; // the n low bits: the columns of the board
long long solutions = 0;
// cols: columns taken; d1, d2: squares of THIS row attacked along the two diagonals
void place(unsigned cols, unsigned d1, unsigned d2) {
if (cols == full) { ++solutions; return; } // a queen in every row
unsigned avail = full & ~(cols | d1 | d2); // the safe squares of this row
while (avail) {
unsigned bit = avail & -avail; // lowest safe square
avail ^= bit;
place(cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1);
}
}
int main() {
int n = 12;
full = (1u << n) - 1;
place(0, 0, 0);
std::printf("%lld\n", solutions); // 14200
}The contest idiom: a row's safe squares are one machine word, avail & -avail isolates the lowest set bit, and shifting the diagonal masks by one moves the attacks down a row. It counts all 14,772,512 solutions for in a few seconds.
You list the subsets of a set of integers, some of them negative, whose sum is exactly , deciding the items one by one. Which pruning test is safe?
- Abandon a partial subset whose sum exceeds
- Stop extending a partial subset as soon as its sum equals
- Abandon a partial subset if its sum plus all the remaining positive items is still below
- With the items sorted, abandon when the next item alone exceeds minus the partial sum
Show the answer
C. Abandon a partial subset if its sum plus all the remaining positive items is still below
Adding the remaining positive items is the most any completion can add, so if even that falls short of , no extension reaches : every extendable partial subset passes the test. The other three tests are safe only when all items are positive.
Sudoku, duplicates and symmetry
Sudoku is n-queens with more kinds of constraint: each of the 81 cells takes a digit from 1 to 9, and no row, column or box may repeat a digit. The search fills one empty cell per level, and the order of the cells is free. Use that freedom: always fill the most constrained cell, the one with the fewest digits still allowed. A cell with one candidate costs no branching at all, and a cell with none is a dead end discovered immediately, before any work is wasted below it.
def solve(g): # g: 9 lists of 9 ints, 0 = empty
def options(r, c):
br, bc = r // 3 * 3, c // 3 * 3
used = set(g[r]) | {g[i][c] for i in range(9)} | \
{g[i][j] for i in range(br, br + 3) for j in range(bc, bc + 3)}
return [d for d in range(1, 10) if d not in used]
empty = [(r, c) for r in range(9) for c in range(9) if g[r][c] == 0]
if not empty:
return True # every cell is filled
r, c = min(empty, key=lambda rc: len(options(*rc))) # most constrained cell
for d in options(r, c):
g[r][c] = d # choose
if solve(g): # explore
return True
g[r][c] = 0 # un-choose: no digit works here
return FalseIt recomputes candidates from scratch for clarity, yet on a famously hard puzzle with only 21 givens it finishes in under a second of CPython. Keeping sets or bitmasks per row, column and box makes each test . The Optimal lesson Exact Cover & Dancing Links turns sudoku, n-queens and tiling puzzles into one problem with one solver.
When the input contains equal items, two sibling choices with equal values root identical subtrees, and every solution below them comes out twice. Sort the items first, then at each node skip a choice equal to the previous sibling's choice:
def subsets_with_dup(nums):
nums = sorted(nums) # equal values become neighbors
out, cur = [], []
def go(start):
out.append(cur[:]) # every node is a distinct subset
for j in range(start, len(nums)):
if j > start and nums[j] == nums[j - 1]:
continue # an equal sibling: the same subtree again
cur.append(nums[j])
go(j + 1)
cur.pop()
go(0)
return out
print(subsets_with_dup([1, 2, 2])) # [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]Here each node chooses the next item to add, so every node, not only every leaf, is a subset. Checked against a brute force with a set of sorted tuples on hundreds of random inputs.
Symmetry is duplication in disguise. To split numbers into groups with equal sums, place the numbers one at a time into groups. All empty groups are interchangeable, so try only the first empty group for each number: that alone can save a factor of up to . Placing the largest numbers first helps too, because they have the fewest places to go, so conflicts surface near the root, where pruning cuts the biggest subtrees.
Recognizing it
Backtracking announces itself in the statement and in the constraints:
- "List all", "return every", "generate", "print each": the output itself is a family of subsets, orders or placements, possibly exponentially many.
- A puzzle with rules: place, assign or color things so that constraints hold (n-queens, sudoku, crosswords, coloring with 3 colors). That is a constraint satisfaction problem.
- Tiny inputs: – when candidates are orders, – when they are subsets, or a grid of a few dozen cells. Small limits are a hint that exponential search is intended.
- A path that may not revisit cells in a grid or graph, such as tracing a word through adjacent letters.
| Problem, in brief | Key idea | Cost |
|---|---|---|
| All distinct subsets of a list with repeated values | sort; each node picks the next item; skip equal siblings | |
| All multisets of reusable candidates with sum | nondecreasing choices; stop the loop once a sorted candidate exceeds what remains | output-sensitive; depth at most |
| All balanced strings of pairs of parentheses | add "(" while fewer than are open; add ")" while it would close an open one | one leaf per answer: the Catalan number , 42 for |
| Does a word appear as a path of adjacent cells in a letter grid? | DFS from each cell; mark the cell on the path, unmark it on return | for a word of length |
| Split numbers into groups of equal sum | largest first; skip a group that would overflow; try only one empty group | exponential; fine for about 16 numbers |
Common bugs.
- Forgetting to un-choose: state from one branch leaks into its siblings. Every change made before the recursive call must be undone after it.
- Storing the shared list instead of a copy at a leaf.
- An unsafe prune: "the sum passed the target" is wrong once negative numbers are allowed.
- Duplicates: skipping equal values without sorting first, or with
j > 0instead ofj > start. - Recursion depth: CPython stops at about 1,000 nested calls by default, which a grid DFS can exceed; raise the limit or use an explicit stack.
- Changing a collection while looping over it, such as removing candidates from the set being iterated.
A string of length 16 must be cut into pieces that are all palindromes, and you must return every such way of cutting it. Which approach fits?
- Dynamic programming over prefixes that returns the number of ways
- Greedy: repeatedly cut off the longest palindromic prefix
- Backtracking over the position of the next cut, extending only with palindromic pieces
- A sliding window that grows while the window is a palindrome
Show the answer
C. Backtracking over the position of the next cut, extending only with palindromic pieces
The output can be exponential: a string of 16 equal letters can be cut in ways, every one of them valid. Backtracking produces each way once, and a precomputed table of which substrings are palindromes makes each test .
Key takeaways
- Backtracking walks the state-space tree depth first: choose, explore, un-choose, with only the current path in memory.
- Its running time is (nodes visited) × (work per node): nodes for subsets and for permutations, so – and – are the practical limits by the rule of thumb.
- A pruning test is safe when every partial candidate that extends to a solution passes it; on 6 queens, checking each queen as it is placed cuts 55,987 nodes to 153.
- Sort and skip equal siblings to avoid duplicate solutions, try the most constrained choice first, and break symmetries such as interchangeable empty groups.
- Signals: "list all", "every", small , puzzles with rules. Look-alikes: counting with repeated subproblems (dynamic programming), shortest paths (BFS), one arrangement with a known construction (a formula).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A backtracking search lists all permutations of 5 distinct items, appending one unused item per level. How many nodes does its tree have, the root included?
- 120
- 206
- 326
- 3,906
Show the answer
C. 326
Depth holds ordered prefixes: .
In the subsets function of this lesson, the line out.append(cur[:]) is changed to out.append(cur). What does subsets([1, 2, 3]) return?
- The same 8 subsets as before
- Eight copies of
[1, 2, 3] - Eight empty lists
- It raises an error
Show the answer
C. Eight empty lists
All eight entries refer to the one list cur. Every choose is matched by an un-choose, so when the search returns cur is empty, and every entry shows that empty list. Store a copy at each leaf.
To list the distinct subsets of [1, 2, 2], the search sorts the items and skips a choice equal to the previous one. Written as if j > 0 and nums[j] == nums[j-1]: continue instead of j > start, which subsets go missing?
- None
- [2] and [1, 2]
- [1, 2, 2] and [2, 2]
- Only []
Show the answer
C. [1, 2, 2] and [2, 2]
The skip must apply only between siblings: j > start lets the first choice at each node take any value. With j > 0, the second 2 can never follow the first one down a path, so the subsets that contain both 2s disappear. The correct output is [], [1], [1, 2], [1, 2, 2], [2], [2, 2].
Given a string of at most 12 digits, return every valid IPv4 address you can form by inserting three dots, where each part is 0–255 without leading zeros. Which approach fits?
- Binary search on the position of the first dot
- Backtracking over the length (1, 2 or 3 digits) of each part, pruning invalid parts
- Dynamic programming that counts the valid addresses
- A greedy split that takes three digits per part whenever possible
Show the answer
B. Backtracking over the length (1, 2 or 3 digits) of each part, pruning invalid parts
The answer is a list of all valid splits, and there are at most ways to choose four part lengths, so backtracking with a validity check on each part is simple and instant. For "25525511135" it returns 255.255.11.135 and 255.255.111.35.
Go deeper
- Pruning & Branch and Bound · Feasibility checks, bounds and ordering heuristics that shrink the search tree.
- Exact Cover & Dancing Links · Knuth’s Algorithm X for sudoku, pentominoes and n-queens.
- Meet in the Middle · Split the search into halves: 2^(n/2) for subset sum and more.
Further reading
- D. E. Knuth, The Art of Computer Programming, Vol. 4B: Combinatorial Algorithms, Part 2 (Addison-Wesley, 2022), §7.2.2, "Backtrack programming".
- S. W. Golomb & L. D. Baumert, "Backtrack programming," Journal of the ACM 12(4) (1965), 516–524.
- J. Erickson, Algorithms (2019, free online), chapter 2, "Backtracking".
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 5, "Complete search".