AlgoViz

Backtracking

medium 20 min

Backtracking builds an answer one choice at a time and abandons a partial answer the moment it cannot work.

Chapter mnemonic

Backtracking in three moves

Lay a tile. Try the trail. Lift the tile.

What must you do after returning from exploring a branch?

Undo its choice so the next branch starts from the same state.

Video lesson · Chapter 1 of 6

The chalk mark that must disappear

0:00 / 4:55

Backtracking in 75 seconds

1:26Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Choose. Pick one option for the next decision and add it to the partial answer

Understand it

Start here

What backtracking is

Backtracking builds candidate answers step by step and abandons ("backtracks from") each partial candidate as soon as it can tell it will never become a valid answer. It is how you list every subset, every arrangement, every way to place queens on a board, or find a word hidden in a grid. Under the hood it is plain recursion, so if recursion is new, start with Recursion: Factorial.

  • Decision tree

    Every partial answer is a node and every option is a branch. The search walks this tree to find all the possibilities.

  • Pruning

    A check before each choice. If a branch cannot lead to a valid answer, it is cut off before any work is spent on it.

  • Backtrack

    When a branch is finished or dead, undo the last choice and try the next option at the level above.

The analogy

Solving a maze

Picture yourself in a maze. At each junction you pick a corridor. If you hit a dead end you walk back to the last junction and take a corridor you have not tried. You chalk-mark the junctions you have visited so you never go round in circles. That is the whole algorithm.

One junction in the maze

Walking forward is a choice; walking back is the undo. The visualizer's maze scene runs exactly this, dead end included.

The template

Choose, explore, unchoose

The four moves inside every call
  1. 1Choosetake one option
  2. 2Constrainis it still valid?
  3. 3Explorerecurse one level deeper
  4. 4Unchooseundo it, try the next
Repeat: back to Choose

The loop arrow is the for-loop over options: after the undo, the next option goes through the same four moves.

Python
def backtrack(path, options, result, n):    if len(path) == n:                 # base case: a complete answer        result.append(path[:])         # save a COPY, then stop this branch        return    for x in options:        if x in path:                  # constraint: prune invalid choices before recursing            continue        path.append(x)                 # choose        backtrack(path, options, result, n)   # explore        path.pop()                     # unchooseresult = []backtrack([], [1, 2, 3], result, 3)print(result)    # all 6 orderings of [1, 2, 3]
The template every problem on this page follows. Only the four helper ideas change from problem to problem.
Edit and run it in your browser

What one call does

The "no" arrow from the validity check is pruning: the option is skipped without a call. The return at the bottom is the backtrack.

The picture

The decision tree

Draw every partial answer as a node and every option as an edge and you get a decision tree. The root is the empty answer, each level makes one more decision, and the leaves are complete answers or dead ends. Backtracking visits this tree in depth-first order, exactly like depth-first traversal of a tree, except that the tree is never stored: it exists only as the sequence of calls.

Decision tree for permutations of [1, 2, 3]

From [ ] you can pick 1, 2 or 3; from [1] you can pick 2 or 3; and so on. The six green leaves are the complete answers.

Pattern 1

Subsets: in or out, 2ⁿ

Why there are 2ⁿ subsets

2×2×⋯×2⏟n elements, each in or out=2n,∑k=0n(nk)=2n\underbrace{2 \times 2 \times \cdots \times 2}_{n \text{ elements, each in or out}} = 2^{n}, \qquad \sum_{k=0}^{n} \binom{n}{k} = 2^{n}
Each element is either in a subset or not: two options, nn times. Counting by size gives the same total: 1+3+3+1=81 + 3 + 3 + 1 = 8 for n=3n = 3.

The include / exclude tree for [1, 2, 3]

Three yes-or-no decisions, 23=82^3 = 8 leaves. The visualizer uses the other common shape, a start index that only looks forward, where every node is a subset.
Python
def subsets(nums):    result, path = [], []    def backtrack(start):        result.append(path[:])          # every node is a subset        for i in range(start, len(nums)):            path.append(nums[i])        # choose            backtrack(i + 1)            # explore: only later numbers            path.pop()                  # unchoose    backtrack(0)    return resultprint(subsets([1, 2, 3]))   # [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
The start-index version. Starting the loop at i + 1 means [2, 1] is never built as a copy of [1, 2].
Edit and run it in your browser

There is a whole topic on this pattern, including the bitmask and iterative versions: Subsets and the power set.

Pattern 2

Permutations: order matters, n!

Why there are n! permutations

n⏟1st×(n−1)⏟2nd×⋯×1⏟last=n!,3!=6,  5!=120,  10!=3,628,800\underbrace{n}_{\text{1st}} \times \underbrace{(n-1)}_{\text{2nd}} \times \cdots \times \underbrace{1}_{\text{last}} = n!, \qquad 3! = 6,\; 5! = 120,\; 10! = 3{,}628{,}800
Any of the nn elements can go first, any of the remaining n−1n - 1 second, and so on. Only complete paths of length nn are answers.
PatternHow the loop choosesAnswersCountTime
SubsetsStart index: only later elementsEvery node2n2^nO(n⋅2n)O(n \cdot 2^n)
Combinations of size kkStart index, stop at length kkNodes at depth kk(nk)\binom{n}{k}O(k⋅(nk))O(k \cdot \binom{n}{k})
PermutationsAny unused element (used array)Leaves at depth nnn!n!O(n⋅n!)O(n \cdot n!)
Combination sum (reuse allowed)Start index i, not i + 1Paths with total = targetdepends on targetO(nT/m)O(n^{T/m}) roughly
The extra factor of nn or kk is the cost of copying each answer into the result. In the last row TT is the target and mm the smallest candidate, so T/mT/m bounds the depth.
Python
def permute(nums):    result, path = [], []    used = [False] * len(nums)    def backtrack():        if len(path) == len(nums):            result.append(path[:])            return        for i in range(len(nums)):            if used[i]:                continue            used[i] = True; path.append(nums[i])     # choose            backtrack()                               # explore            path.pop(); used[i] = False               # unchoose    backtrack()    return resultprint(permute([1, 2, 3]))   # 6 lists, from [1, 2, 3] to [3, 2, 1]
Permutations with a used array. Undo both the path and the flag.
Edit and run it in your browser

Pruning

Cut dead branches early

Pruning is the difference between backtracking and brute force. Brute force builds every complete candidate and then checks it. Backtracking checks partial candidates, so one failed check removes the entire subtree below it. A cut near the root saves far more than a cut near the leaves.

Check before you choose

In subset sum on [2, 3, 5, 7] with target 10, the check total + x > target turns 16 possible subsets into 11 calls; the visualizer shows each cut.
TechniqueWhat it doesExample check
Sort firstLets one failed check end the loop, and puts duplicates side by sideif i > start and nums[i] == nums[i - 1]: continue
Early terminationStop as soon as a running total or count goes past the limitif total + nums[i] > target: break
Constraint setsLook up used columns or diagonals in O(1)O(1) instead of scanningif col in cols or r - c in diag: continue
MemoisationCache results when the same sub-state comes back (then it is really DP)if (i, total) in memo: return memo[(i, total)]

How much pruning saves on N-Queens

∑k=0nnk⏟every placement, row by row  vs  calls with pruning:n=4:  341→17,n=8:  19,173,961→2,057\underbrace{\sum_{k=0}^{n} n^{k}}_{\text{every placement, row by row}} \;\text{vs}\; \text{calls with pruning:} \quad n = 4:\; 341 \to 17, \qquad n = 8:\; 19{,}173{,}961 \to 2{,}057
Placing one queen per row with no checks gives 1+n+n2+⋯+nn1 + n + n^2 + \dots + n^n nodes. Checking columns and diagonals before each placement visits only 17 of them for n=4n = 4 and 2,057 for n=8n = 8, while still finding all 2 and all 92 solutions.

Worked example

4-Queens, step by step

Place 4 queens on a 4 × 4 board so that no two share a row, a column or a diagonal. Put exactly one queen in each row, so the only decision per row is the column.

StepBoard (row: column)What happens
10: 0Place a queen at (0, 0). Row 0 done, move to row 1.
20: 0, 1: 2Row 1: columns 0 and 1 are attacked, column 2 is safe.
30: 0, 1: 2Row 2: all four cells are attacked. Backtrack: move row 1's queen to column 3.
40: 0, 1: 3, 2: 1Row 2 takes column 1, but then row 3 has no safe cell. Every option under (0, 0) fails.
50: 1, 1: 3, 2: 0, 3: 2Move row 0's queen to column 1. Now each row finds a safe column: a solution.
Queens at (0, 1), (1, 3), (2, 0), (3, 2). The only other solution for n=4n = 4 is its mirror image, columns [2, 0, 3, 1].

Two queens share a diagonal when

∣r1−r2∣=∣c1−c2∣⟺r1−c1=r2−c2   or   r1+c1=r2+c2|r_1 - r_2| = |c_1 - c_2| \quad\Longleftrightarrow\quad r_1 - c_1 = r_2 - c_2 \;\text{ or }\; r_1 + c_1 = r_2 + c_2
Along a down-right diagonal r−cr - c stays the same; along a down-left one r+cr + c stays the same. Keep one set of used columns and one set for each diagonal kind, and every safety check is O(1)O(1).
Python
def count_n_queens(n):    cols, diag, anti = set(), set(), set()    def place(row):        if row == n:            return 1        total = 0        for col in range(n):            if col in cols or row - col in diag or row + col in anti:                continue                                  # prune            cols.add(col); diag.add(row - col); anti.add(row + col)        # choose            total += place(row + 1)                                         # explore            cols.remove(col); diag.remove(row - col); anti.remove(row + col)  # unchoose        return total    return place(0)print([count_n_queens(n) for n in range(1, 9)])   # [1, 0, 0, 2, 10, 4, 40, 92]
Count the solutions for n = 1 to 8.
Edit and run it in your browser

Grids

Word search and mazes

On a grid the options are the four neighbours: up, down, left and right. The state you must undo is the visited mark. Word Search marks a cell by overwriting it with # and puts the letter back when the call returns; the maze marks cells in a seen set.

One call of dfs(r, c, k) in Word Search

Searching ABCCED in the grid ABCE / SFCS / ADEE marks six cells on the way down and restores all six on the way back.

Cost of Word Search

O(R⋅C⋅4⋅3L−1)⊆O(R⋅C⋅4L) time,O(L) spaceO\big(R \cdot C \cdot 4 \cdot 3^{L-1}\big) \subseteq O\big(R \cdot C \cdot 4^{L}\big) \text{ time}, \qquad O(L) \text{ space}
Every one of the R⋅CR \cdot C cells can start a path; the first step has 4 directions and every later step at most 3, because you never step back onto the cell you came from. The recursion is LL deep for a word of length LL.

Complexity

Exponential time, linear space

The general bound

T=O(bd) nodes×work per node,S=O(d)T = O\big(b^{d}\big) \text{ nodes} \times \text{work per node}, \qquad S = O(d)
With at most bb options per decision and dd decisions, the tree has at most 1+b+b2+⋯+bd=O(bd)1 + b + b^2 + \dots + b^d = O(b^d) nodes. Space is only the current path and dd stack frames.
ProblemTimeSpaceWhy
SubsetsO(n⋅2n)O(n \cdot 2^n)O(n)O(n)2n2^n answers, each copied in O(n)O(n)
PermutationsO(n⋅n!)O(n \cdot n!)O(n)O(n)n!n! leaves, each copied in O(n)O(n)
N-QueensO(n!)O(n!)O(n)O(n)Row kk has at most n−kn - k free columns
Word SearchO(R⋅C⋅4L)O(R \cdot C \cdot 4^L)O(L)O(L)Up to 3 new directions per letter
Sudoku (9 × 9)O(9m)O(9^{m}) for mm empty cellsO(m)O(m)Pruning makes real puzzles fast
Space counts the path and the stack, not the output. Storing all 2n2^n subsets of course needs O(n⋅2n)O(n \cdot 2^n) memory.

Choosing a technique

When to use backtracking

Perfect for

  • Finding all solutions, or all arrangements.
  • Constraint satisfaction: Sudoku, N-Queens, scheduling.
  • Generating permutations, combinations and subsets.
  • Puzzles, game trees and finding any path in a maze.

Use something else when

  • You need the shortest path: use BFS.
  • Subproblems overlap: use dynamic programming.
  • A greedy choice is provably safe: use greedy.
  • You need a real-time answer, or only one solution and a direct formula exists.
TechniqueExploresBest for
BacktrackingAll paths, cutting invalid onesAll solutions, constraints
Depth-first searchAs deep as possible firstAny path, connectivity
Breadth-first searchLevel by levelShortest path (unweighted)
Dynamic programmingEach subproblem once, cachedCounting, min / max, yes / no
GreedyOne best local choice per stepWhen local best = global best
Backtracking explores exhaustively and restores a mutable state; DP builds answers up from a table. N-Queens and Word Search are backtracking; coin change and LCS are DP.

Is it a backtracking problem?

Words that point to backtracking: "all", "every", "generate", "arrangements", "valid placement", "partition into".
  • Combination Sum

    Reuse allowed, so recurse with i, not i + 1. Sort and break when a candidate exceeds what is left.

  • Palindrome Partitioning

    Choose where the next piece ends; only recurse if the piece is a palindrome. aab gives a|a|b and aa|b.

  • Generate Parentheses

    Add ( while opens are left, add ) while it would still balance. The counts are the constraint.

  • Sudoku Solver

    Choose a digit for the next empty cell, check row, column and box, undo on failure.

Recap

Key takeaways

Key points

  • Backtracking is DFS over a tree of choices that abandons a partial answer as soon as it cannot work.
  • Every call: check for a complete answer, then for each option choose, explore, unchoose.
  • Save a copy of the path (path[:]), never the path itself.
  • Prune before choosing; with sorted input a failed check can break the whole loop.
  • Subsets: start index, 2ⁿ answers. Permutations: used array, n! answers.
  • Time is exponential, O(bᵈ) nodes; space is O(d) for the current path.
  • Grid search marks a cell, recurses into the four neighbours, then restores it.
  • Shortest path means BFS, overlapping subproblems mean DP: backtracking is for all solutions and constraints.

Sources