Sub topic 15
Backtracking Without Recursion
Every backtracking algorithm in this tutorial so far has used recursion. The call stack has stored the current depth and the next choice to try at each level, and returning from a call has worked as the signal to undo a choice. This chapter shows how to hold that same information in a stack you manage yourself.
This chapter assumes you are comfortable with the choose-explore-unchoose template, the recursive subset and N-Queens solvers from earlier chapters, and Python lists used as stacks (append and pop).
Why Replace Recursion at All
Recursion is usually the clearest way to write backtracking, so treat the iterative form as a tool for specific situations. These are the ones that come up most:
| Reason | What goes wrong with recursion | What the explicit stack gives you |
|---|---|---|
| Deep searches | CPython's default recursion limit is 1000 frames, so a path longer than that raises `RecursionError` | The depth is limited only by heap memory |
| Pausing and resuming | A recursive search can't easily stop partway and continue later | The whole search state is an ordinary object you can keep, inspect, or save |
| Languages or runtimes without cheap recursion | Some embedded or GPU settings limit stack size or forbid recursion | The code is a plain loop |
| Debugging | The state is spread across many frames | One list shows the entire frontier |
You can raise the limit with sys.setrecursionlimit, but the C stack underneath can still overflow and crash the interpreter. The explicit stack avoids that risk.
What the Call Stack Was Storing
A recursive backtracking call keeps three things:
- The depth. This is how many choices have been made so far.
- The loop position. At each level, this is the index of the next choice to try.
- The shared state. This is
path,used, the occupied-column sets, and so on.
The shared state already lives outside the frames, so it can stay as it is. To replace recursion, you need a stack that holds the loop position of every active level. The stack's length then gives the depth.
The translation follows from that:
- "Call
backtrackfor the child" becomes pushing a new frame. - "The
forloop moves to its next value" becomes incrementing the number in the top frame. - "The loop ends and the function returns" becomes popping the frame and undoing the choice that created it.
Subsets With a Stack of Loop Indices
In the recursive subset generator, each call recorded path and then looped i from start to the end. In the iterative version, stack[d] holds the next index to try at depth d.
def subsets_iterative(nums):
result = [[]] # the empty subset is recorded at the root
path = []
stack = [0] # stack[d] = next index to try at depth d
while stack:
i = stack[-1]
if i < len(nums):
stack[-1] = i + 1 # advance this level's loop
path.append(nums[i]) # choose
result.append(path[:]) # record the new partial subset
stack.append(i + 1) # explore: child starts after i
else:
stack.pop() # this level's loop is finished
if stack:
path.pop() # unchoose the parent's choice
return result
print(subsets_iterative([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]The output order matches the recursive version exactly. That is a useful test of a conversion. If the iterative code visits nodes in the same order as the recursive code, the two are traversing the same state-space tree in the same depth-first way.
The if stack: guard depends on an invariant: len(stack) == len(path) + 1 at all times. Each non-root frame was created by one append to path. When the root frame is popped, no choice is left to undo.
N-Queens With Explicit Undo
N-Queens has more state to restore: the three sets of attacked columns and diagonals. The frame layout is the same, with stack[row] holding the next column to try in that row. A queens list remembers where each placed queen went, so the undo step knows which entries to remove from the sets.
def n_queens_iterative(n):
cols, diag1, diag2 = set(), set(), set()
queens = [] # queens[r] = column of the queen in row r
stack = [0] # stack[r] = next column to try in row r
count = 0
while stack:
row = len(stack) - 1
col = stack[-1]
if row == n or col == n:
if row == n:
count += 1 # every row has a queen
stack.pop()
if stack: # undo the queen that led here
c = queens.pop()
r = len(queens)
cols.remove(c)
diag1.remove(r - c)
diag2.remove(r + c)
continue
stack[-1] = col + 1 # advance before testing
if col in cols or (row - col) in diag1 or (row + col) in diag2:
continue # pruned: try the next column
queens.append(col)
cols.add(col)
diag1.add(row - col)
diag2.add(row + col)
stack.append(0) # explore the next row
return count
print(n_queens_iterative(8)) # 92
print(n_queens_iterative(0)) # 1 (the empty board)The frame's index is advanced before the validity test. If the code advanced only after a successful placement, a pruned column would be tested forever. Advancing first means that a continue always makes progress.
Snapshot Stacks: Trading Memory for Simplicity
The frame approach keeps one shared mutable state and undoes changes explicitly. You can also push complete, immutable states onto the stack. Then you never need to undo anything, because each popped item already contains everything its subtree needs.
def permutations_iterative(nums):
result = []
stack = [((), tuple(nums))] # (path so far, remaining elements)
while stack:
path, remaining = stack.pop()
if not remaining:
result.append(list(path))
continue
# Push in reverse so the first choice is popped (explored) first.
for i in reversed(range(len(remaining))):
child_path = path + (remaining[i],)
child_rest = remaining[:i] + remaining[i + 1:]
stack.append((child_path, child_rest))
return result
print(permutations_iterative([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]The reversed push keeps the output in the same order as the recursive version. Without it, the search still visits every leaf, but it explores the last choice at each level first.
The two styles have different strengths:
| Property | Frame stack with undo | Snapshot stack |
|---|---|---|
| Undo logic | Required and easy to get wrong | None |
| Memory | O(depth) frames plus one shared state | All siblings of every node on the path are stored, each as an O(n) copy, so permutations take O(n³) |
| Work per step | O(1) to advance and apply | O(n) to build each child copy |
| Pruning | Tested when a choice is tried | Can be tested before pushing, so invalid children never enter the stack |
| Fit | Large state such as Sudoku boards and grids | Small state, or when correctness matters more than speed |
Making the Search Resumable
Because all of the search state lives in local variables, you can turn the frame-based loop into a generator by changing result.append(...) to yield. The caller can then take the first k solutions and stop, or pause between solutions, without the search ever running deeper than the stack you control.
def subsets_lazy(nums):
path = []
stack = [0]
yield []
while stack:
i = stack[-1]
if i < len(nums):
stack[-1] = i + 1
path.append(nums[i])
yield path[:]
stack.append(i + 1)
else:
stack.pop()
if stack:
path.pop()
gen = subsets_lazy(list(range(30))) # 2**30 subsets in total
print([next(gen) for _ in range(4)])
# [[], [0], [0, 1], [0, 1, 2]]A recursive generator using yield from is also lazy, but it still nests one Python frame per level, so it hits the same recursion limit on deep searches.
Checklist for Converting a Recursive Solver
- List the parameters of the recursive call. Each one either goes into the frame or can be derived from the stack length.
- Find the loop variable in the recursive function. Its current value is what the frame stores.
- Advance the frame before testing a choice.
- On a pop, undo the choice that created the frame, not a choice inside it.
- Compare the output order against the recursive version on small inputs.
Exercise
In subsets_iterative, suppose you remove the if stack: guard and always call path.pop() after stack.pop(). What happens when the input is [1, 2]?
Show answer
The search runs correctly until the last step. Then the root frame is popped while path is already empty, and path.pop() raises IndexError: pop from empty list. The guard is needed because the root frame was not created by any choice, so popping it has nothing to undo.
Exercise
Convert combination_sum(candidates, target) from the earlier chapter to a frame-based iterative version. Candidates are distinct positive integers that may be reused, and the sorted-input break must be kept. What should each frame store, and how is the break expressed?
Show answer
Each frame stores the next candidate index to try at that depth. The remaining sum can be kept as a running variable that is decreased on choose and increased on undo. When the remaining sum reaches 0, record path[:] and pop the frame. If the frame's index reaches len(candidates), or candidates[i] > remaining, pop the frame: because the input is sorted, the break means the whole level is exhausted. Otherwise set stack[-1] = i + 1, append candidates[i] to path, subtract it from remaining, and push a child frame starting at i, not i + 1, so the same candidate can be reused. On every pop where the stack is still non-empty, remove the last element from path and add it back to remaining.
Exercise
Why does the snapshot-stack version of permutations need no undo step, while nqueensiterative does?
Show answer
Each item on the snapshot stack holds its own copies of path and remaining, built as new tuples, so no two stack entries share mutable state. Nothing a child does can affect its siblings. nqueensiterative keeps one shared set of columns and diagonals for the whole search, so it must remove a queen's entries before a sibling placement is tested.