Sub topic 8
Pruning: Abandoning Hopeless Branches Early
This chapter assumes you know the choose-explore-unchoose template and the subset and combination generators from earlier chapters. It also assumes you can read Big-O notation. The chapter covers what pruning is, where the check belongs in the template, how to measure its effect, and the bugs it most often causes.
What Pruning Means
A backtracking algorithm walks a state-space tree. Each node is a partial solution, and each edge is one choice. Without pruning, the algorithm visits every node and tests a candidate only after building it in full.
Pruning means you stop exploring a node once you can prove that nothing below it can become a valid answer. You skip the whole subtree under that node, not just one leaf. When the tree branches widely, cutting a subtree near the root can remove millions of nodes.
A pruning rule is safe only if it never discards a branch that contains a valid answer. A rule that is fast but sometimes wrong gives you wrong results, not a faster correct algorithm.
Two Kinds of Pruning Rule
Most pruning rules fall into two families.
| Kind | Question it answers | Example |
|---|---|---|
| Feasibility (constraint) pruning | Does this partial solution already break a rule? | The running sum already exceeds the target. A queen attacks another queen. |
| Bound pruning | Can this partial solution still reach a complete answer? | Too few elements remain to fill k slots. The remaining values cannot add up to the target. |
Feasibility pruning rejects a node because of something that is already true about it. Bound pruning rejects a node because of what can no longer happen below it. Both are safe as long as the reasoning behind them is sound.
Measuring the Effect: Feasibility Pruning
The function below finds every subset of positive integers that sums to a target. With prune=False it visits every subset and checks the sum at every node. With prune=True it sorts the input and stops the loop as soon as the next value would push the sum past the target. A counter records how many calls each version makes.
def subset_sum(nums, target, prune):
# Assumes nums are positive integers; each may be used at most once.
nums = sorted(nums)
result, path = [], []
calls = 0
def backtrack(start, total):
nonlocal calls
calls += 1
if total == target:
result.append(path[:])
if prune:
return # positive values: any extension overshoots
for i in range(start, len(nums)):
if prune and total + nums[i] > target:
break # sorted: every later value overshoots too
path.append(nums[i])
backtrack(i + 1, total + nums[i])
path.pop()
backtrack(0, 0)
return result, calls
nums = [3, 5, 6, 7, 9, 11, 12, 15, 18, 20]
brute, brute_calls = subset_sum(nums, 20, prune=False)
fast, fast_calls = subset_sum(nums, 20, prune=True)
print(fast) # [[3, 5, 12], [3, 6, 11], [5, 6, 9], [5, 15], [9, 11], [20]]
print(brute == fast) # True
print(brute_calls) # 1024
print(fast_calls) # 43The unpruned version makes 2^10 = 1024 calls, one for each subset. The pruned version makes 43 calls, one for each subset whose sum is at most 20. Both return the same six answers. With pruning, the cost depends on how many partial sums stay under the target, not on the input size alone.
Why `break` and not `continue`
The break is only correct because the list is sorted and every value is positive. If nums[i] overshoots, then nums[i+1] and every later value overshoot as well, so the rest of the loop is dead. With unsorted input you could only use continue, which skips one child and still tests the rest. Sorting costs O(n log n) once and turns many per-child tests into a single early exit.
Measuring the Effect: Bound Pruning
Bound pruning asks whether a node can still finish. In the problem of choosing k numbers from 1..n, a path of length j needs k - j more elements. If fewer elements remain after start, no complete answer lies below. The fix is to shorten the loop range so that hopeless children are never created.
def combine(n, k, prune):
result, path = [], []
calls = 0
def backtrack(start):
nonlocal calls
calls += 1
if len(path) == k:
result.append(path[:])
return
need = k - len(path)
stop = n - need + 1 if prune else n # last index that leaves room
for i in range(start, stop):
path.append(i + 1)
backtrack(i + 1)
path.pop()
backtrack(0)
return result, calls
slow, slow_calls = combine(10, 8, prune=False)
fast, fast_calls = combine(10, 8, prune=True)
print(len(fast)) # 45
print(slow == fast) # True
print(slow_calls) # 1013
print(fast_calls) # 165Without the bound, the search visits every subset of size 8 or less: 1024 minus the 11 subsets of size 9 or 10, which gives 1013. With the bound, it visits only prefixes that can still be extended to 8 elements, which comes to 165 calls. The gain is largest when k is close to n, because most short paths then cannot fill the remaining slots.
Where the Check Belongs
You can place a pruning check in one of two spots.
- At the top of the call. Enter the child, test it, and return if it fails. This is simple, and it is the only option when the test needs the child's full state.
- Inside the loop, before the recursive call. Test the candidate choice and skip it without recursing. This saves a function call, the stack frame, and the append and pop for every rejected child.
Both versions explore the same set of valid nodes. The second also avoids creating rejected nodes, and it allows break when the choices are ordered. Prefer it when the test is cheap to run on the candidate alone.
Failure Modes
These are the most common pruning bugs.
- Over-pruning. The rule rejects a branch that contains an answer. Typical causes are an off-by-one in a bound (
>where>=was needed) or an assumption that does not hold, such as positive values or sorted input. - Pruning before recording. If the check runs before the "is this a solution?" test, a node that is both complete and at the limit can be discarded. In
subset_sum, the equality test comes before the loop for this reason. - Leaking state on early return. A pruning
returnplaced after a state change but before the matching undo leaves the shared path corrupted. Make each change and its undo bracket only the recursive call. - Checks that cost more than they save. A test that scans the whole board on every node can turn an O(1) step into an O(n) one. Keep incremental state, such as a running sum or sets of occupied columns, so each test is constant time. The N-Queens chapter uses this technique.
- Comparing only on tiny inputs. Pruning often has no visible effect on small examples. Test on inputs large enough for the counts to differ.
Pruning and Complexity
Pruning rarely improves the worst-case Big-O bound. Subset sum is still O(2^n) in the worst case, because some inputs never trigger a cut. Pruning changes the number of nodes actually visited, and on real inputs that number can be orders of magnitude smaller. When you report the cost of a pruned search, give both the worst-case bound and a measured node count on typical inputs.
Exercise
In subset_sum, suppose nums may contain zeros but no negative numbers. Is the break still safe? Is the early return after recording still safe?
Show answer
The break is still safe. If total + nums[i] > target, every later value is at least nums[i], so it also overshoots. The early return is not safe. Adding a zero to a path that already sums to the target yields another valid subset, and the return would skip it. Remove the return, or handle zeros separately.
Exercise
You need all subsets of distinct positive integers that sum to target, and you also know the sum of nums[start:] for every start. Write a bound-pruning test for the top of backtrack(start, total), and explain why it is safe.
Show answer
Precompute suffix[i] = sum(nums[i:]) with suffix[len(nums)] = 0, then add if total + suffix[start] < target: return after the equality check. Even taking every remaining element cannot reach the target, so no subset below this node can be a solution.
Exercise
In combine, why does the pruned loop stop at n - need + 1 rather than n - need?
Show answer
range excludes its upper limit. The last useful index i must leave need - 1 elements after it, so i + 1 + (need - 1) <= n, which gives i <= n - need. To include index n - need, the range must stop at n - need + 1.