Lesson 10: Backtracking — Subsets, Permutations and N-Queens
Backtracking is recursion with choices. At each step you try one option, recurse to explore what follows, and then undo the choice — backtrack — and try the next option. It is the systematic way to explore every possibility, and it solves a whole family of problems: listing all subsets, all orderings, all ways to place queens on a chessboard so none attack each other. The key insight is that the undo step is as important as the choice: without it, each branch of the search would be polluted by the previous one.
The cleanest example is generating all subsets of a set. For each item, you have two choices: include it, or leave it out. The recursive function walks through the items one by one, building the current subset as it goes, and records a copy of the subset at every step. The example below lists all eight subsets of [1, 2, 3]. Notice the pattern: choose, recurse, un-choose. That three-line rhythm is the whole technique.
def subsets(items):
result = []
def backtrack(index, current):
result.append(list(current)) # record a copy of the current subset
for i in range(index, len(items)):
current.append(items[i]) # choose
backtrack(i + 1, current) # explore
current.pop() # un-choose (backtrack)
backtrack(0, [])
return result
print(subsets([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
Pruning: the art of giving up early
Trying every possibility is expensive — a set of 20 items has over a million subsets — so the real skill in backtracking is pruning: recognising a dead end early and abandoning that branch without exploring it. In the N-Queens problem, where you place queens so none share a row, column or diagonal, you stop as soon as a new queen attacks an existing one; there is no point placing the remaining queens. In a maze, you stop when you hit a wall. Pruning does not change the answer, only the time it takes to find it, and a well-pruned backtracking solution can be the difference between finishing in a second and never finishing at all.
Backtracking also teaches an important lesson about copying. The subset example appends list(current) — a copy — because current keeps changing as the search continues; appending the list itself would record the same object eight times, and all eight entries would end up as the final, empty list. That is a classic beginner bug, and it is worth understanding deeply: in Python, variables hold references, and when you store a list you store a reference to a living object, not a snapshot. Copy when you mean snapshot.
Going further
Generating permutations is the natural partner to generating subsets, and it uses the same choose–explore–un-choose rhythm. At each position you try every unused item, recurse to fill the next position, and then un-choose. The only difference is the bookkeeping: instead of an index that moves forward, you keep track of which items have been used, often with a boolean list or a set. The number of permutations grows fast — ten items have over three million — which is a useful reminder that backtracking is a tool for small inputs, and that pruning matters even more here than with subsets.
Backtracking is also the engine behind constraint satisfaction problems: puzzles like Sudoku, crosswords, and timetabling, where each choice must satisfy rules that involve other choices. The algorithm is the same — choose a value, check the constraints, recurse, undo — and the pruning is what makes it work: a Sudoku solver that places a digit and immediately checks the row, column and box will explore a tiny fraction of the possibilities a blind search would. The pattern is worth recognising, because constraint problems appear in contests dressed as puzzles, scheduling, and layout.
Pruning deserves a concrete example, because it is the difference between a backtracking solution that finishes and one that does not. In the N-Queens problem, a solver that places queens row by row and checks for attacks after each placement explores only a few thousand partial placements, where a blind search would try millions of complete ones. The check costs almost nothing and saves almost everything. Whenever you write a backtracking search, ask what you can test early: the earlier a dead end is detected, the less of the tree you have to explore.
Key Terms
- Backtracking
- Exploring every possibility by choosing, recursing, and undoing the choice to try the next option.
- Pruning
- Abandoning a branch of the search early once it is clear it cannot lead to a solution.
- Subset
- A selection of some (possibly none, possibly all) items from a set; n items have 2^n subsets.
- Permutation
- An ordering of items; n items have n! permutations.
- N-Queens
- The problem of placing n queens on an n by n board so none attack each other.
- Choose–explore–un-choose
- The three-step rhythm of backtracking: make a choice, recurse, then undo it.
- Snapshot vs reference
- Storing a copy of a list freezes its current contents; storing the list itself keeps a live reference.
Discussion Questions
- Why must the subset example append list(current) instead of current? What would the result look like without the copy?
- How does pruning change the running time of a backtracking search without changing its answer?
- A set of 20 items has about a million subsets. What does that tell you about the limits of backtracking, and when is it still the right tool?
Practice Questions
- How many subsets does a set of 4 items have?
- In the subsets code, what does
current.pop()do, and why is it essential? - Why is the result recorded at every call, not just at the deepest one?
- In N-Queens, what is a good pruning test after placing a new queen?
- How many permutations do 4 distinct items have?
Show answers
- 16, which is 2^4. Each item is independently in or out, giving two choices per item.
- It undoes the choice just made, restoring the state for the next option. Without it, choices would accumulate and later branches would include items they should not.
- Because every prefix of choices is itself a valid subset. The empty set, [1], [1, 2] and so on are all recorded as the search passes through them.
- Check whether it attacks any queen already placed (same row, column or diagonal). If it does, abandon the branch immediately — no completion of it can be valid.
- 24, which is 4! = 4 × 3 × 2 × 1. The first position has 4 choices, the next 3, then 2, then 1.