Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Backtracking

Build a solution one choice at a time, and undo the dead ends.

There are (648)=4,426,165,368\binom{64}{8} = 4{,}426{,}165{,}368 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: 2n+1−12^{n+1}-1 for subsets, ⌊e⋅n!⌋\lfloor e \cdot n! \rfloor 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.

text
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-choose

Un-choose restores pp 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.

python
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 nn 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:

ProblemChoice at depth iiLeavesNodesListing everything
Subsets of nn itemsinclude or exclude item ii2n2^n2n+1−12^{n+1}-1Θ(n⋅2n)\Theta(n \cdot 2^n)
Permutations of nn distinct itemsany unused itemn!n!⌊e⋅n!⌋\lfloor e \cdot n! \rfloorΘ(n⋅n!)\Theta(n \cdot n!)
kk-combinations of nn itemsan item larger than the last one(nk)\binom{n}{k}∑i≤k(ni)\sum_{i \le k} \binom{n}{i} without the "enough left" testO(k(nk))O(k \binom{n}{k}) with the test
Placements of nn queens, one per row, never checked earlyany columnnnn^nnn+1−1n−1\frac{n^{n+1}-1}{n-1}hopeless beyond n≈9n \approx 9
With the "enough items left" test, every node of the combination tree leads to at least one solution, so the tree has at most kk nodes per leaf: the search is output-sensitive.
DerivationCounting the permutation tree
  1. N(n)  =  ∑i=0nn!(n−i)!  =  n!∑j=0n1j!N(n) \;=\; \sum_{i=0}^{n} \frac{n!}{(n-i)!} \;=\; n! \sum_{j=0}^{n} \frac{1}{j!}

    A node at depth ii is an ordered choice of ii distinct items out of nn, so depth ii holds n!/(n−i)!n!/(n-i)! nodes. Summing over the depths and writing j=n−ij = n - i:

  2. n!∑j>n1j!  =  1n+1+1(n+1)(n+2)+⋯  <  1n  ≤  1(n≥1)n! \sum_{j > n} \frac{1}{j!} \;=\; \frac{1}{n+1} + \frac{1}{(n+1)(n+2)} + \cdots \;<\; \frac{1}{n} \;\le\; 1 \qquad (n \ge 1)

    The series for ee is ∑j≥01/j!\sum_{j \ge 0} 1/j!. What the finite sum leaves out is tiny:

  3. N(n)  =  ⌊e⋅n!⌋,T(n)  =  Θ(n⋅n!)N(n) \;=\; \lfloor e \cdot n! \rfloor, \qquad T(n) \;=\; \Theta(n \cdot n!)

    So N(n)N(n) is the integer just below e⋅n!e \cdot n!. Only a fraction 1/e≈37%1/e \approx 37\% of the nodes are leaves, and the search does Θ(n)\Theta(n) work per leaf to copy a permutation out:

Predict before you look

How many nodes, the root included, does the permutation tree of 4 distinct items have?

Show the answer

65

Level by level: 1+4+12+24+24=651 + 4 + 12 + 24 + 24 = 65, which is ⌊24e⌋=⌊65.24⌋\lfloor 24e \rfloor = \lfloor 65.24 \rfloor. 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 rr is the column of row rr's queen. Squares on one diagonal share r−cr - c, and squares on one anti-diagonal share r+cr + c. Three sets make every attack test O(1)O(1):

python
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 89−17=19,173,961\frac{8^9 - 1}{7} = 19{,}173{,}961 nodes of the tree that checks only full boards.

cpp
#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 n=16n = 16 in a few seconds.

Check your understanding

You list the subsets of a set of integers, some of them negative, whose sum is exactly TT, deciding the items one by one. Which pruning test is safe?

  1. Abandon a partial subset whose sum exceeds TT
  2. Stop extending a partial subset as soon as its sum equals TT
  3. Abandon a partial subset if its sum plus all the remaining positive items is still below TT
  4. With the items sorted, abandon when the next item alone exceeds TT minus the partial sum
Show the answer

C. Abandon a partial subset if its sum plus all the remaining positive items is still below TT

Adding the remaining positive items is the most any completion can add, so if even that falls short of TT, no extension reaches TT: 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 3×33 \times 3 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.

python
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 False

It 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 O(1)O(1). 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:

python
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 kk 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 k!k!. 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: n≤10n \le 10–1212 when candidates are orders, n≤20n \le 20–2525 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 briefKey ideaCost
All distinct subsets of a list with repeated valuessort; each node picks the next item; skip equal siblingsO(n⋅2n)O(n \cdot 2^n)
All multisets of reusable candidates with sum TTnondecreasing choices; stop the loop once a sorted candidate exceeds what remainsoutput-sensitive; depth at most T/min⁡T / \min
All balanced strings of nn pairs of parenthesesadd "(" while fewer than nn are open; add ")" while it would close an open oneone leaf per answer: the Catalan number CnC_n, 42 for n=5n = 5
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 returnO(R⋅C⋅3L)O(R \cdot C \cdot 3^{L}) for a word of length LL
Split numbers into kk groups of equal sumlargest first; skip a group that would overflow; try only one empty groupexponential; fine for about 16 numbers
In each row the search never generates an invalid candidate in full: the choose step only offers moves that keep the partial candidate valid.

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 > 0 instead of j > 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.
Check your understanding

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?

  1. Dynamic programming over prefixes that returns the number of ways
  2. Greedy: repeatedly cut off the longest palindromic prefix
  3. Backtracking over the position of the next cut, extending only with palindromic pieces
  4. 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 215=32,7682^{15} = 32{,}768 ways, every one of them valid. Backtracking produces each way once, and a precomputed table of which substrings are palindromes makes each test O(1)O(1).

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): 2n+1−12^{n+1}-1 nodes for subsets and ⌊e⋅n!⌋\lfloor e \cdot n! \rfloor for permutations, so n≈20n \approx 20–2525 and n≈10n \approx 10–1111 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 nn, 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.

Question 1

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?

  1. 120
  2. 206
  3. 326
  4. 3,906
Show the answer

C. 326

Depth ii holds 5!/(5−i)!5!/(5-i)! ordered prefixes: 1+5+20+60+120+120=326=⌊120e⌋1 + 5 + 20 + 60 + 120 + 120 = 326 = \lfloor 120e \rfloor.

Question 2

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?

  1. The same 8 subsets as before
  2. Eight copies of [1, 2, 3]
  3. Eight empty lists
  4. 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.

Question 3

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?

  1. None
  2. [2] and [1, 2]
  3. [1, 2, 2] and [2, 2]
  4. 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].

Question 4

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?

  1. Binary search on the position of the first dot
  2. Backtracking over the length (1, 2 or 3 digits) of each part, pruning invalid parts
  3. Dynamic programming that counts the valid addresses
  4. 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 34=813^4 = 81 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

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".