Backtracking
medium 20 minBacktracking 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
Backtracking in 75 seconds
1:26Reel
How it works
Step through the idea, or press Play.
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
The template
Choose, explore, unchoose
- 1Choosetake one option
- 2Constrainis it still valid?
- 3Explorerecurse one level deeper
- 4Unchooseundo it, try the next
The loop arrow is the for-loop over options: after the undo, the next option goes through the same four moves.
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]What one call does
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]
[ ] 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
The include / exclude tree for [1, 2, 3]
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]]i + 1 means [2, 1] is never built as a copy of [1, 2].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
| Pattern | How the loop chooses | Answers | Count | Time |
|---|---|---|---|---|
| Subsets | Start index: only later elements | Every node | ||
| Combinations of size | Start index, stop at length | Nodes at depth | ||
| Permutations | Any unused element (used array) | Leaves at depth | ||
| Combination sum (reuse allowed) | Start index i, not i + 1 | Paths with total = target | depends on target | roughly |
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]used array. Undo both the path and the flag.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
[2, 3, 5, 7] with target 10, the check total + x > target turns 16 possible subsets into 11 calls; the visualizer shows each cut.| Technique | What it does | Example check |
|---|---|---|
| Sort first | Lets one failed check end the loop, and puts duplicates side by side | if i > start and nums[i] == nums[i - 1]: continue |
| Early termination | Stop as soon as a running total or count goes past the limit | if total + nums[i] > target: break |
| Constraint sets | Look up used columns or diagonals in instead of scanning | if col in cols or r - c in diag: continue |
| Memoisation | Cache 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
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.
| Step | Board (row: column) | What happens |
|---|---|---|
| 1 | 0: 0 | Place a queen at (0, 0). Row 0 done, move to row 1. |
| 2 | 0: 0, 1: 2 | Row 1: columns 0 and 1 are attacked, column 2 is safe. |
| 3 | 0: 0, 1: 2 | Row 2: all four cells are attacked. Backtrack: move row 1's queen to column 3. |
| 4 | 0: 0, 1: 3, 2: 1 | Row 2 takes column 1, but then row 3 has no safe cell. Every option under (0, 0) fails. |
| 5 | 0: 1, 1: 3, 2: 0, 3: 2 | Move row 0's queen to column 1. Now each row finds a safe column: a solution. |
Two queens share a diagonal when
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]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
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
Complexity
Exponential time, linear space
The general bound
| Problem | Time | Space | Why |
|---|---|---|---|
| Subsets | answers, each copied in | ||
| Permutations | leaves, each copied in | ||
| N-Queens | Row has at most free columns | ||
| Word Search | Up to 3 new directions per letter | ||
| Sudoku (9 × 9) | for empty cells | Pruning makes real puzzles fast |
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.
| Technique | Explores | Best for |
|---|---|---|
| Backtracking | All paths, cutting invalid ones | All solutions, constraints |
| Depth-first search | As deep as possible first | Any path, connectivity |
| Breadth-first search | Level by level | Shortest path (unweighted) |
| Dynamic programming | Each subproblem once, cached | Counting, min / max, yes / no |
| Greedy | One best local choice per step | When local best = global best |
Is it a backtracking problem?
Combination Sum
Reuse allowed, so recurse with
i, noti + 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.
aabgivesa|a|bandaa|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.