Sub topic 4
Undoing Changes and Copying Results Correctly
This chapter assumes you can write recursive functions in Python, know that lists are mutable and passed by reference, and have seen the choose-explore-unchoose template from the previous chapter. It covers the bugs that show up when that template is applied carelessly, and the rules that prevent them.
Backtracking is fast because it shares one mutable state, such as a path list, a used array, or a board, across the whole search. Each call changes that state a little, explores, and then changes it back. This sharing creates two duties. You must restore the state exactly, and you must copy the state whenever you want to keep it.
The Restoration Invariant
One rule covers correct state handling:
- When a recursive call returns, every piece of shared state must be exactly as it was when the call began.
If every call keeps this rule, each sibling branch starts from the same state its parent saw. The search then behaves as if each branch had its own private copy, without paying for the copies. If any call breaks the rule, later branches inherit stale choices and the output goes wrong silently.
Bug 1: Storing a Reference Instead of a Copy
The most common backtracking bug is appending the shared list itself to the results:
def broken_subsets(nums):
result = []
path = []
def backtrack(start):
result.append(path) # bug: stores a reference to the shared list
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return result
print(broken_subsets([1, 2]))
# [[], [], [], []]The count is right, since [1, 2] has four subsets, but every entry is the same list object. By the time the search finishes, the pops have emptied it. The result holds four views of one empty list.
The fix is to take a snapshot at the moment of recording:
result.append(path[:]) # or list(path), or path.copy()Shallow and Deep Copies
path[:] is a shallow copy. It builds a new outer list that holds the same elements. That is enough when the elements are immutable, such as integers or strings. It is not enough when the state is nested. A Sudoku or N-Queens board stored as a list of lists needs every row copied:
board = [[1, 2], [3, 4]]
shallow = board[:] # new outer list, same row objects
deep = [row[:] for row in board] # new outer list and new rows
board[0][0] = 99
print(shallow[0][0]) # 99, because the row is shared
print(deep[0][0]) # 1, because the row was copiedFor irregular nested structures, copy.deepcopy works but is slower. A comprehension that matches the known shape is usually the better choice.
Bug 2: Forgetting to Undo
If you drop the pop(), every choice stays in path for the rest of the search:
def no_undo(nums):
result, path = [], []
def backtrack(start):
result.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1) # missing path.pop()
backtrack(0)
return result
print(no_undo([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 3], [1, 2, 3, 3, 2],
# [1, 2, 3, 3, 2, 3], [1, 2, 3, 3, 2, 3, 3]]The first four results look right, which makes the bug easy to miss. After that, each sibling branch starts on top of the leftovers from the branch before it.
Undo Everything, in Reverse Order
Many searches change more than one piece of state per choice. The permutations template sets used[i] and appends to path. N-Queens adds to three sets. Every change made in the "choose" step needs a matching change in the "unchoose" step.
Undo the changes in the reverse order you made them, like a stack:
used[i] = True # do 1
path.append(nums[i]) # do 2
backtrack()
path.pop() # undo 2
used[i] = False # undo 1With independent structures the order often makes no difference to correctness. Reverse order still matters as a habit, because some state does depend on what came before. One example is a running total computed from path[-1]. Another is an undo that reads a value the earlier change set.
Make the Undo Exactly Inverse
An undo has to reverse what the choose step actually did. That is not always the same as the opposite operation. Suppose a word search tracks visited letters in a set instead of visited cells:
seen = {'A'}
seen.add('A') # no effect: 'A' was already there
seen.remove('A') # removes 'A', which the caller still needed
print(seen) # set()add did nothing, but remove deleted state that belonged to an earlier choice. When values can repeat, use a counter and increment and decrement it. The alternative is to record whether the add changed anything and undo only in that case.
from collections import Counter
counts = Counter({'A': 1})
counts['A'] += 1 # choose
counts['A'] -= 1 # unchoose
print(counts['A']) # 1, the caller's state is intactBug 3: Returning Early Without Restoring
Searches that stop at the first solution often return as soon as a child succeeds. If the return comes before the undo, the state is never restored:
def exist_leaky(board, word):
rows, cols = len(board), len(board[0])
def backtrack(r, c, k):
if k == len(word):
return True
if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[k]:
return False
saved = board[r][c]
board[r][c] = '#'
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
if backtrack(r + dr, c + dc, k + 1):
return True # bug: leaves '#' on the board
board[r][c] = saved
return False
return any(backtrack(r, c, 0) for r in range(rows) for c in range(cols))
grid = [list('AB'), list('CD')]
print(exist_leaky(grid, 'ABD')) # True
print(grid) # [['#', '#'], ['C', '#']]
print(exist_leaky(grid, 'ABD')) # False, because the board is corruptedThe first answer is correct. The caller's board is damaged, though, so the second call on the same board fails. try/finally guarantees the restore on every exit path, including early returns and exceptions:
def exist(board, word):
rows, cols = len(board), len(board[0])
def backtrack(r, c, k):
if k == len(word):
return True
if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[k]:
return False
saved = board[r][c]
board[r][c] = '#'
try:
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
if backtrack(r + dr, c + dc, k + 1):
return True
return False
finally:
board[r][c] = saved
return any(backtrack(r, c, 0) for r in range(rows) for c in range(cols))
grid = [list('AB'), list('CD')]
print(exist(grid, 'ABD')) # True
print(grid) # [['A', 'B'], ['C', 'D']]
print(exist(grid, 'ABD')) # TrueThe Alternative: Pass New Objects Down
You can avoid undo entirely by never mutating. Each call receives its own new path:
def subsets_copying(nums):
result = []
def backtrack(start, path):
result.append(path) # safe: no one ever mutates this list
for i in range(start, len(nums)):
backtrack(i + 1, path + [nums[i]])
backtrack(0, [])
return result
print(subsets_copying([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]Here result.append(path) is correct, because path + [x] builds a new list and nothing modifies it afterward. Passing tuples gives the same safety, and the language enforces it.
| Strategy | Cost per choice | Risk | Good fit |
|---|---|---|---|
| Mutate and undo (`append`/`pop`) | O(1) | Missing or mismatched undo | Large or deep searches, boards, sets of constraints |
| Pass a new copy (`path + [x]`) | O(length of path) | Extra memory and copying | Short paths, clarity first, concurrent exploration |
| Mutate, snapshot at record time | O(1) per choice, O(k) per result | Forgetting the snapshot | The standard template for enumeration problems |
For enumeration problems that record every node, such as subsets, copying at each call costs about the same as snapshotting, because every node gets copied either way. The gap grows when most nodes are pruned or never recorded, as in N-Queens or Sudoku. There, copying a board at every step wastes work that mutate-and-undo avoids.
A Checklist for Every Backtracking Function
- List every piece of state the choose step changes.
- Write the matching undo for each, in reverse order, right after the recursive call.
- Check that every
returnbetween the choose and the undo either restores state or is deliberately allowed to leave it. - Copy the state when you record it, deeply enough for its shape.
- Test on a tiny input and compare the full output, not just its length.
Exercise
A permutations function records results with result.append(path) and correctly calls path.pop() and used[i] = False after each recursive call. What does it print for [1, 2, 3], and why?
Show answer
It prints six empty lists, [[], [], [], [], [], []]. Every entry is a reference to the single shared path list, and the pops have emptied that list by the time the search ends. Recording path[:] fixes it.
Exercise
An N-Queens solver records each solution with solutions.append(board[:]), where board is a list of lists of '.' and 'Q', and it clears each queen after its recursive call. Every stored solution comes out blank. Explain the cause and give a fix.
Show answer
board[:] copies only the outer list, so each stored solution shares its row lists with the live board. When the solver removes queens while backtracking, the stored rows change too. Copy each row with [row[:] for row in board], or store each row as an immutable string with [''.join(row) for row in board].
Exercise
A choose step runs cols.add(col) and the unchoose step runs cols.remove(col). Under what condition does this pair break the restoration invariant, and how would you make it safe?
Show answer
It breaks when col was already in cols before the add. The add then has no effect, but the remove deletes an entry that an earlier choice still needs. Either check col not in cols before choosing, which N-Queens does anyway, or replace the set with a Counter and increment and decrement it.