Sub topic 13
Analyzing the Cost of Backtracking
This chapter assumes you can read Big-O notation, follow recursive Python code, and recognize the subset, permutation, combination-sum, and N-Queens solvers from earlier chapters. The goal is to estimate a backtracking algorithm's running time and memory before you run it. You will also learn to measure the real cost when the estimate is too loose to trust.
The Core Formula
A backtracking algorithm is a depth-first walk over a state-space tree. Its running time comes from three things:
- Nodes visited. Each node is one call to
backtrack, which is one partial solution. - Work per node. This is the loop overhead, the constraint checks, and any appends and pops.
- Output cost. Copying
path[:]into the result takes time proportional to the length of the path.
Written as a formula:
time ≈ (nodes visited) × (work per node) + (number of solutions) × (cost to copy one)Most analysis mistakes come from forgetting the last term. An algorithm that visits 2^n nodes and copies a list of length up to n at each node runs in O(n · 2^n) time, not O(2^n).
Counting Nodes for the Standard Generators
Subsets
The subset generator records a result at every node, and every node corresponds to exactly one subset. There are 2^n subsets, so there are 2^n nodes. Each node copies a path of average length n/2. The total time is O(n · 2^n).
Permutations
At depth k the permutation tree has n!/(n−k)! nodes: n choices for the first slot, n−1 for the second, and so on. Summing over k = 0..n gives:
1 + n + n(n-1) + ... + n! = n! × (1/n! + 1/(n-1)! + ... + 1/0!) ≈ e × n!So the tree has about 2.718 × n! nodes. Each node also runs a loop of length n over the used array, and each of the n! leaves copies a path of length n. Both terms give O(n · n!).
Combination sum
The tree's shape depends on the values in the input, not only on how many there are. With target T and smallest candidate m, a path can be at most ⌊T/m⌋ deep, because each step subtracts at least m. The branching factor is at most n, which gives an upper bound of O(n^(T/m)). The bound is valid but loose. Sorting the candidates and breaking early cuts many branches, and the real count is usually far smaller.
Measuring Instead of Guessing
For pruned searches, a closed formula is often too loose to be useful. Counting calls is cheap and exact. The script below instruments three solvers from earlier chapters.
from math import factorial, e
def count_subset_nodes(n):
nodes = 0
def backtrack(start):
nonlocal nodes
nodes += 1
for i in range(start, n):
backtrack(i + 1)
backtrack(0)
return nodes
def count_permutation_nodes(n):
nodes = 0
used = [False] * n
def backtrack(depth):
nonlocal nodes
nodes += 1
if depth == n:
return
for i in range(n):
if not used[i]:
used[i] = True
backtrack(depth + 1)
used[i] = False
backtrack(0)
return nodes
def count_queens_nodes(n):
cols, diag1, diag2 = set(), set(), set()
per_level = [0] * (n + 1)
def backtrack(row):
per_level[row] += 1
if row == n:
return
for col in range(n):
if col in cols or (row - col) in diag1 or (row + col) in diag2:
continue
cols.add(col); diag1.add(row - col); diag2.add(row + col)
backtrack(row + 1)
cols.remove(col); diag1.remove(row - col); diag2.remove(row + col)
backtrack(0)
return per_level
for n in range(1, 7):
print(n, count_subset_nodes(n), 2 ** n,
count_permutation_nodes(n), int(e * factorial(n)))
levels = count_queens_nodes(8)
print(levels, sum(levels))
# [1, 8, 42, 140, 344, 568, 550, 312, 92] 2057The first loop confirms that the subset tree has exactly 2^n nodes and that the permutation tree has ⌊e · n!⌋ nodes. The N-Queens output is more interesting. Placing one queen per row with no pruning would give a permutation tree of about e × 8! ≈ 109,600 nodes. Brute force over every placement of 8 queens in 8 rows is 8^8 ≈ 16.7 million. Pruning on diagonals cuts the real tree to 2,057 nodes.
In an unpruned tree, each level is larger than the one above it. Here the counts peak at depth 5 and then shrink. A peak like this shows that the constraints are cutting branches.
Space Complexity
Space has two parts, and you should report them separately:
- Auxiliary space. This covers the recursion stack, the current
path, and bookkeeping such asusedor the diagonal sets. All of it grows with the tree's depth, not with the number of nodes. For subsets and permutations this is O(n). For N-Queens it is O(n) for the stack plus O(n) for the three sets. - Output space. This is whatever you store in
result. All subsets together hold n · 2^(n−1) elements. All permutations hold n · n!.
The output usually dominates. If you only need a count, or only need to process each solution once, yield solutions or increment a counter instead of collecting lists. The time stays exponential, but memory falls back to O(n).
Summary Table
| Problem | Nodes visited | Work per node | Total time | Auxiliary space |
|---|---|---|---|---|
| Subsets of n | 2^n | O(1) loop step + O(n) copy | O(n · 2^n) | O(n) |
| Permutations of n | ≈ e · n! | O(n) scan of `used` | O(n · n!) | O(n) |
| Combinations C(n, k) | ≤ sum of C(n, i) for i ≤ k | O(1) + O(k) copy at leaves | O(k · C(n, k)) for large k | O(k) |
| Combination sum, target T, min m | ≤ n^(T/m) | O(1) + copy at leaves | Input-dependent | O(T/m) |
| N-Queens, one per row | ≤ e · n!, far fewer in practice | O(n) loop, O(1) checks | Bounded by O(n · n!) | O(n) |
| Sudoku with k empty cells | ≤ 9^k | O(1) to O(27) validity check | O(9^k) worst case | O(k) stack |
Common Analysis Errors
- Counting leaves instead of nodes. In the subset tree, every node is a solution. In the permutation tree, internal nodes add a constant factor of about e − 1. In heavily pruned trees, most nodes are dead ends that are never solutions.
- Ignoring per-node work. A
usedscan of length n, or a validity check that walks a whole row, multiplies the node count. The set-based checks in N-Queens exist to keep this cost at O(1). - Treating the worst case as typical. Sudoku's 9^k bound is technically correct and useless in practice. Real puzzles with 50 empty cells solve in milliseconds because constraints prune nearly every branch. Pruning rarely changes the worst-case Big-O, but it often changes the observed cost by orders of magnitude.
- Forgetting the sort. Sorting for pruning or duplicate skipping costs O(n log n). That is negligible next to an exponential search, but include it for completeness.
Exercises
Exercise
The combinations generator picks k elements from n by recursing with start = i + 1 and recording a result when len(path) == k. Ignoring any pruning on the remaining length, how many nodes does the tree have, and what is the total cost of copying results?
Show answer
A node at depth i is a subset of size i, so the tree has the sum of C(n, i) for i = 0..k nodes. Only the C(n, k) leaves at depth k are copied, at O(k) each, so copying costs O(k · C(n, k)). With the pruning check "stop if not enough elements remain", every node lies on a path to some leaf, and when k is close to n/2 the total cost becomes O(k · C(n, k)).
Exercise
You call combination_sum([1, 50], 100). Give the maximum recursion depth and explain whether Python's default recursion limit is a concern.
Show answer
The smallest candidate is 1, so the deepest path subtracts 1 a hundred times: depth 100, plus 1 for the root call. That is well below the default limit of about 1000. With target 2000 and candidate 1, the depth would pass 2000 and raise RecursionError, even though the number of distinct solutions stays small.
Exercise
Modify countqueensnodes so it also returns the total number of constraint checks (iterations of the inner for loop). For n = 8, why should this number be about 8 times the number of internal nodes?
Show answer
Increment a counter on every iteration of the for loop, before the conflict test. Every internal node (rows 0 through 7) runs the loop exactly 8 times, whether or not the square is attacked. The leaves at row 8 return before the loop. The internal nodes number 2057 − 92 = 1965, so there are 1965 × 8 = 15,720 checks. This shows why the per-node cost belongs in the formula: there are 7.6 times as many checks as nodes.