Sub topic 4
Undoing Changes and Copying Results Correctly
This chapter assumes you can write recursive Python functions and that you know the choose-explore-unchoose template from the previous chapter. It covers the two bugs that break most first attempts at backtracking: saving a result that later changes under you, and forgetting to undo a choice.
One Shared Path, Many Branches
Most backtracking code keeps a single mutable list, path, for the whole search. Each recursive call appends one choice, explores, and then pops that choice. Sharing one list is cheap because no call copies anything. The catch is that path keeps changing until the search ends.
The function below generates every bit string of length n, and it contains the most common bug:
def bits_buggy(n):
result, path = [], []
def backtrack():
if len(path) == n:
result.append(path) # BUG: stores a reference, not a snapshot
return
for b in (0, 1):
path.append(b)
backtrack()
path.pop()
backtrack()
return result
print(bits_buggy(2)) # [[], [], [], []]Each entry in result points to the same list object. After the last pop() that object is empty, so all four entries print as [].
Snapshot at the Moment of Recording
The fix is to copy the path at the moment you record it:
def bits(n):
result, path = [], []
def backtrack():
if len(path) == n:
result.append(path[:]) # snapshot of the current state
return
for b in (0, 1):
path.append(b)
backtrack()
path.pop()
backtrack()
return result
print(bits(2)) # [[0, 0], [0, 1], [1, 0], [1, 1]]path[:], list(path), and path.copy() all make a shallow copy. A shallow copy is enough when the elements are immutable values such as integers or strings. If the path holds mutable objects that you also change during the search, use copy.deepcopy, or better, store immutable values in the path.
Every Change Needs an Undo
The rule is that a call must leave all shared state exactly as it found it. That rule covers more than path:
- A
usedarray or a set of taken columns must be unmarked after the recursive call. - A grid cell marked as visited must get its original value back.
- Undo changes in the reverse order you made them, so that dependent state unwinds correctly.
- Undo on every exit path. If a call can return early, restore the state before the
return, or save the return value in a variable, restore the state, and then return it.
If you forget an undo, sibling branches start from a corrupted state. In bits, dropping path.pop() makes path keep growing. The len(path) == n check then never matches again, and the recursion runs until Python raises RecursionError.
Alternative: Pass New Objects Instead of Mutating
You can avoid undo steps completely by passing a fresh list down each call: backtrack(path + [b]). Nothing shared changes, so you have nothing to restore, and you can append path directly.
| Approach | Undo needed | Copy cost | Typical use |
|---|---|---|---|
| Shared mutable path | Yes | One copy per recorded result | Large searches, interview-standard code |
| New list per call | No | O(depth) per call | Short paths, clarity first |
Exercise
A solver appends path (not a copy) to result only when it finds a solution, and then immediately returns True all the way up without popping. The single stored result looks correct. Why does it work here, and why is it still fragile?
Show answer
It works because the search stops right after recording, so nothing mutates path again. The stored list is the live path, frozen only because nothing pops it. The code breaks as soon as someone changes it to collect all solutions or to keep using path after it returns. A copy makes the code correct whatever happens next.
Exercise
A call sets used[i] = True, appends nums[i], and recurses. Write the two undo lines in the correct order.
Show answer
path.pop() followed by used[i] = False. This reverses the order of the changes. Here the two are independent, so either order runs correctly, but reverse order is the safe habit when changes depend on each other.