Backtracking: Subsets, Permutations and N-Queens in Python
Some problems ask for every solution, not just one: all subsets of a set, all orderings of a list, every way to place queens on a board so that none attack each other. There is no shortcut around generating them, but there is a clean, general way to do it. Backtracking builds a candidate one choice at a time, explores everything that follows from that choice, then undoes it and tries the next one. When a partial candidate already breaks a rule, it abandons that whole branch, which is called pruning.
Backtracking is recursion over a tree of choices, so it helps to be comfortable with recursion first. Examples use Python 3.10 or later and only the standard library.
The template: choose, explore, un-choose
Every backtracking function has the same three moves around a shared partial solution:
- Choose: make one decision and record it (append to the current list, mark a value as used, place a queen).
- Explore: recurse to make the remaining decisions.
- Un-choose: reverse exactly what step 1 did, so the shared state is back to how it was before the choice.
Plus a base case: when the partial solution is complete, record a copy of it. Keeping one mutable list and undoing changes is what makes backtracking cheap in memory: the state is O(n) no matter how many solutions there are.
Subsets and permutations
Subsets
For each item there are two choices, include it or leave it out, so a set of n items has 2^n subsets. The recursion decides item i, then item i + 1, and so on, and records the subset once every item has been decided.
Permutations
A permutation chooses, at each position, one of the items not used yet: n choices for the first position, n - 1 for the second, and so on, for n! permutations. A used list marks which items are taken; un-choosing clears the mark.
def subsets(items):
out, current = [], []
def explore(i):
if i == len(items):
out.append(list(current))
return
current.append(items[i]) # choose: include items[i]
explore(i + 1) # explore
current.pop() # un-choose
explore(i + 1) # explore without it
explore(0)
return out
def permutations(items):
out, current, used = [], [], [False] * len(items)
def explore():
if len(current) == len(items):
out.append(list(current))
return
for i, x in enumerate(items):
if used[i]:
continue
used[i] = True # choose
current.append(x)
explore() # explore
current.pop() # un-choose
used[i] = False
explore()
return out
print(subsets([1, 2, 3]))
print(permutations([1, 2, 3]))
[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Three items give 2^3 = 8 subsets (including the empty one, last) and 3! = 6 permutations. Note out.append(list(current)): appending current itself would store the same list object eight times, and after the un-choose steps they would all end up empty. That missing copy is the most common backtracking bug.
For real work, Python's itertools.combinations and itertools.permutations generate these directly. Writing them by hand is worth doing once, because the same template handles problems no library function covers.
How much work is that?
The running time is the number of nodes in the tree of choices times the work per node. Subsets produce 2^n results and copying each costs up to O(n), so listing them all is O(n x 2^n). Permutations produce n! results, so listing them is O(n x n!). The recursion depth is n either way, so the extra space beyond the output is O(n).
These numbers grow very fast. The Big O Complexity Analyzer evaluates 2^n at n = 10 as 1,024 and n! as 3,628,800; at n = 20, 2^n is already 1,048,576. No pruning fixes a problem whose answer itself has 2^n entries, since you have to write them all down.
N-Queens: pruning in action
Place n queens on an n by n board so that no two share a row, a column or a diagonal. Since every row must hold exactly one queen, the search places one queen per row, top to bottom, and tries each column. Before placing, it checks whether the square is attacked, and skips it if so. Three sets make that check O(1):
cols: columns already used;diag: values of row - column already used (constant along each down-right diagonal);anti: values of row + column already used (constant along each down-left diagonal).
def n_queens(n):
cols, diag, anti = set(), set(), set()
solutions = 0
placements = 0
def place(row):
nonlocal solutions, placements
if row == n:
solutions += 1
return
for c in range(n):
if c in cols or row - c in diag or row + c in anti:
continue # prune: this square is attacked
placements += 1
cols.add(c); diag.add(row - c); anti.add(row + c)
place(row + 1)
cols.remove(c); diag.remove(row - c); anti.remove(row + c)
place(0)
return solutions, placements
for n in range(4, 9):
print(n, n_queens(n))
4 (2, 16)
5 (10, 53)
6 (4, 152)
7 (40, 551)
8 (92, 2056)
Each line shows n, the number of solutions, and the number of queens actually placed during the search. The solution counts, 2, 10, 4, 40 and 92 for n = 4 to 8, are the known values for this puzzle (note that 6 has fewer solutions than 5).
Pruning makes a large difference. With one queen per row and no checks, there are 8^8 = 16,777,216 ways to fill an 8 by 8 board; requiring different columns still leaves 8! = 40,320 permutations to test. The pruned search places a queen only 2,056 times, because a conflict near the top of the board cuts off every arrangement below it.
Pruning lowers the work, not the worst case
It is tempting to read those numbers as "N-Queens is fast now". Pruning helps a great deal in practice, but it shrinks the tree without changing its exponential character: the placement counts above still grow by a factor of three to four with each extra row, and exploring every branch this way stays exponential as n grows. For subsets and permutations, where every leaf is a valid answer, there is nothing to prune at all. The honest bound for backtracking is the size of the search tree, which is exponential in the worst case.
Good pruning rules share one property: they are cheap to check and they cut early. Common ones:
- Constraint checks before recursing, as with the attacked squares above.
- Bounds: in a subset-sum search over sorted positive numbers, stop extending a branch as soon as its sum exceeds the target, since every later item only adds more.
- Symmetry: skip choices that produce mirror images of solutions already counted, when only distinct shapes are needed.
- Duplicate skipping: when the input has repeated values, skip a value equal to the one just tried at the same depth, so the same subset is not generated twice.
When backtracking is the right tool
Backtracking is the intended solution when the problem asks for all solutions, or for any solution of a constraint puzzle, and the input is small: tens of items for subsets, around ten for permutations. When it asks only for a count or an optimum and the subproblems overlap (the number of ways, the fewest coins, the longest subsequence), dynamic programming is usually much faster. Many NP-hard problems are solved exactly by backtracking with strong pruning when n is small.
The Interview Complexity Estimator maps "backtracking / subsets" to O(2ⁿ) time and O(n) space, and "generating permutations" to O(n!) and O(n). It labels both "Hard" even in its small regime; that label is the site's heuristic for exponential classes, not a judgment that backtracking is the wrong approach. For a small n it often is the right one.
Common mistakes
- Not copying the solution before storing it (see above).
- An incomplete un-choose: removing a queen from
colsbut not fromdiagleaves the state wrong for every later branch. - Checking constraints only at the leaves: correct, but it gives up all the benefit of pruning.
- Deep recursion: depth is n, which is fine for the small n backtracking suits; if n is in the thousands, the problem needs a different method anyway.
Check yourself
- How many subsets does a 20-item set have, and is listing them reasonable? (2^20 = 1,048,576. That is feasible, but each extra item doubles it, and 40 items would give more than a trillion.)
- Why does N-Queens need no check for rows? (The search places exactly one queen per row by construction.)
- Squares (2, 5) and (4, 3): same diagonal? (Row + column is 7 for both, so they share an anti-diagonal.)