Sub topic 3
The Choose, Explore, Unchoose Template
The previous chapter treated a search problem as a tree of partial solutions. This chapter turns that tree into code. Nearly every backtracking algorithm in this tutorial uses the same three-step loop: choose an option, explore everything that follows from it, then unchoose it so the next option starts from a clean state. Once you can write this loop from memory, the later problems only differ in what the state is and which options are allowed.
This chapter assumes you can write recursive Python functions with base cases, use lists as stacks with append and pop, and read a state-space tree as described in the previous chapter.
The Three Moves
A backtracking function keeps one shared, mutable partial solution. Each call to the function stands for one node in the state-space tree. That node's partial solution is whatever the shared state holds when the call begins.
- Choose. Pick one candidate and apply it to the shared state. This moves you from a node to one of its children.
- Explore. Call the function recursively. The recursive call explores the whole subtree under that child.
- Unchoose. Reverse the change from step 1. The state now matches the parent node again, so the loop can try the next candidate.
Before the loop, a base case checks whether the current state is a complete solution. If it is, the function records it and returns without branching further.
A Minimal Working Example
The smallest useful problem that shows the template is this: list every string of length n built from a given alphabet. Every leaf in its tree is a solution, and there are no constraints, so nothing distracts from the three moves.
def sequences(alphabet, n):
result = []
path = [] # the shared partial solution
def backtrack():
if len(path) == n: # base case: complete solution
result.append(''.join(path))
return
for ch in alphabet: # candidates at this level
path.append(ch) # choose
backtrack() # explore
path.pop() # unchoose
backtrack()
return result
print(sequences('ab', 3))
# ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']The result is in lexicographic order because the loop tries candidates in alphabet order, and depth-first search finishes each subtree before moving to the next sibling.
Tracing the Calls
Here is the trace for sequences('ab', 2). The depth column is the number of active backtrack frames below the outer call.
| Step | Action | `path` after action | Depth |
|---|---|---|---|
| 1 | choose `a` | `['a']` | 1 |
| 2 | choose `a` | `['a', 'a']` | 2 |
| 3 | record `aa`, return | `['a', 'a']` | 2 |
| 4 | unchoose | `['a']` | 1 |
| 5 | choose `b` | `['a', 'b']` | 2 |
| 6 | record `ab`, return | `['a', 'b']` | 2 |
| 7 | unchoose | `['a']` | 1 |
| 8 | loop ends, return | `['a']` | 1 |
| 9 | unchoose | `[]` | 0 |
| 10 | choose `b`, and so on | `['b']` | 1 |
Each unchoose step puts path back to the value it had just before the matching choose step. That invariant makes the template correct: when a call returns, the shared state is exactly what it was when the call began.
The Four Slots You Fill In
Every backtracking problem fills the same four slots. If you name them before you write code, the code is usually short.
| Slot | Question to answer | In `sequences` |
|---|---|---|
| State | What describes a partial solution? | `path`, a list of characters |
| Base case | When is the state a complete solution? | `len(path) == n` |
| Candidates | Which choices extend the current state? | every character in `alphabet` |
| Undo | How do you reverse one choice exactly? | `path.pop()` |
The state often has more than one part. In later chapters you will see a used array next to the path for permutations, and sets of attacked columns and diagonals for N-Queens. The rule is the same for every part: anything the choose step changes, the unchoose step must restore, in reverse order.
Three Shapes of the Same Template
The base case and the return value change with the question you are asking. The choose, explore, unchoose core stays the same.
Find All
This is the shape shown above. The function returns nothing and appends each complete solution to a result list.
Count
If you only need the number of solutions, return a count instead of building a list. This saves the memory used for stored results.
def count_sequences(alphabet, n):
path = []
def backtrack():
if len(path) == n:
return 1
total = 0
for ch in alphabet:
path.append(ch)
total += backtrack()
path.pop()
return total
return backtrack()
print(count_sequences('abc', 4)) # 81Find One
To stop at the first solution, have the function return a boolean and pass True back up the stack as soon as a solution is found.
def find_first(alphabet, n, accept):
path = []
def backtrack():
if len(path) == n:
return accept(path)
for ch in alphabet:
path.append(ch)
if backtrack():
return True # keep path as the answer: skip the undo on purpose
path.pop()
return False
return ''.join(path) if backtrack() else None
print(find_first('abc', 3, lambda p: p[0] == 'b' and p.count('c') == 2))
# bccIn this shape the undo is skipped on purpose when a solution is found, because the shared state is the answer you want to keep. The undo still runs on every failed branch. The Sudoku solver later in the tutorial uses this shape: it leaves the filled board in place when it succeeds.
Common Errors
Most backtracking bugs break the invariant that a call leaves the state as it found it.
| Bug | Symptom | Fix |
|---|---|---|
| Missing unchoose | `path` grows across siblings. In `sequences`, the length passes `n` and never equals it again, so recursion runs until `RecursionError`. | Pair every choose with an unchoose. |
| Early `return` between choose and unchoose in a find-all search | Later siblings start from a corrupted state. Results are missing or wrong. | Only return early in find-one mode, or undo before returning. |
| Unchoose placed inside an `if` | The undo runs only on some paths, so the state drifts. | Put the unchoose at the same indentation level as the choose. |
| Undo in the wrong order with multi-part state | One part is restored against the wrong value. | Undo in reverse order of the changes. |
| Recording `path` instead of a copy | Every stored result ends up the same, usually empty. | Store `path[:]` or a converted value such as `''.join(path)`. |
The last bug is common enough that the next chapter covers it in detail, along with the choice between undoing a mutation and passing a fresh copy into each call.
Why Mutate and Undo Instead of Copying?
You could avoid undo entirely by passing a new list to each call, for example backtrack(path + [ch]). That works, but every call then pays O(depth) time and memory to build its copy. Mutating one shared list makes each choose and unchoose O(1) and keeps only one partial solution in memory, plus the call stack. For deep trees or large states such as a 9×9 board, the difference is large. The cost is that you must keep the invariant yourself, and the template's structure is how you keep it.
Exercises
Exercise
Using the template, write binary_strings(n) that returns every string of '0' and '1' of length n, in lexicographic order. Name the four slots before writing the code. What does binary_strings(2) return?
Show answer
State: a list path of characters. Base case: len(path) == n. Candidates: '0' and '1'. Undo: path.pop(). Code: def binary_strings(n): then result, path = [], [], then def backtrack(): containing if len(path) == n: result.append(''.join(path)); return followed by for ch in '01': path.append(ch); backtrack(); path.pop(). Call backtrack() and return result. binary_strings(2) returns ['00', '01', '10', '11'].
Exercise
A student moves path.pop() out of the loop in sequences so that it runs once after the loop finishes. What happens when you call sequences('ab', 2), and why?
Show answer
After the first child returns, path is not restored, so the next sibling starts from a longer path. The b branch under a begins from ['a', 'a'], becomes ['a', 'a', 'b'], and its length passes 2. The base case never fires again, the loop keeps appending, and the recursion goes deeper until Python raises RecursionError. One pop per call only removes one of the several appends that call made, so the invariant that a call leaves the state unchanged is broken.
Exercise
In find_first, why is it correct to return True without calling path.pop(), when skipping the undo is a bug in find-all mode?
Show answer
Once a solution is found, every frame on the stack returns True right away, so no sibling branch runs again and nothing will ever read the state expecting the parent's value. The unrestored path holds the solution the caller wants. In find-all mode the loop keeps going after a solution, so a sibling would start from a corrupted state.