Sub topic 1
Recursion and the Call Stack, Revisited
Backtracking is recursion used in a specific way. A function makes one choice, calls itself to handle the rest of the problem, and then picks up where it left off when that call returns. Before you can write a backtracking algorithm and trust it, you need a clear picture of what happens in memory during each call and each return. This chapter rebuilds that picture with backtracking in mind.
Prerequisites
This chapter assumes you can already:
- Write functions and loops in Python or a similar language.
- Read a basic recursive function and point to its base case.
- Use lists, sets, and two-dimensional arrays.
- Read Big-O notation such as O(n) and O(2^n).
You do not need any earlier exposure to backtracking.
What a Stack Frame Holds
Each time Python calls a function, it creates a stack frame. A stack frame is a block of memory that belongs to that single call. Python pushes the frame onto the call stack, which is the list of calls that have started and not yet finished. When the call returns, Python pops its frame and continues in the caller's frame, at the line right after the call.
| Part of a frame | What it stores | Why backtracking cares |
|---|---|---|
| Parameters | The arguments for this call | Each call has its own copy of the names, which makes them natural "current position" markers |
| Local variables | Names assigned inside the call, including loop counters | A loop in a frame remembers which choice it was on while deeper calls run |
| Return point | Where execution resumes in the caller | This is how the algorithm "goes back" to try the next option |
The last row matters most. Backtracking does not need any special "go back" instruction. A return pops a frame, and the caller's loop moves on to its next choice.
Watching Calls Enter and Exit
The function below prints a line on entry and on exit. The indentation shows how deep the stack is.
def trace(n, depth=0):
indent = " " * depth
print(f"{indent}enter trace({n})")
if n == 0:
print(f"{indent}base case")
else:
trace(n - 1, depth + 1)
print(f"{indent}exit trace({n})")
trace(2)Output:
enter trace(2)
enter trace(1)
enter trace(0)
base case
exit trace(0)
exit trace(1)
exit trace(2)Code before the recursive call runs on the way down. Code after it runs on the way back up, in reverse order. Backtracking depends on this split. You make a choice before the recursive call and undo it after the call returns.
Branching Recursion Is Depth-First
trace makes one recursive call per frame. Backtracking functions usually make several, one for each available choice. The function below builds every binary string of length n:
def binary_strings(n, prefix=""):
if len(prefix) == n:
print(prefix)
return
binary_strings(n, prefix + "0")
binary_strings(n, prefix + "1")
binary_strings(2)
# 00
# 01
# 10
# 11The second call, the one with "1", cannot start until the first call and every call beneath it have returned. So the program follows one line of choices all the way to the bottom before it tries an alternative. This order is called depth-first. Because of it, the stack only holds the frames along the current line of choices. It never holds the whole set of possibilities.
For a string of length n, the deepest point of the stack holds n + 1 frames for binary_strings: one for each prefix length from 0 to n. The total number of calls is about 2^(n+1). Space grows with the depth and time grows with the number of calls. You will use this distinction again when you analyze backtracking costs.
Where State Lives: Per-Frame Versus Shared
In binary_strings, prefix + "0" creates a new string. The caller's prefix stays the same, so the caller never has to clean up after the child. Passing immutable values this way undoes changes for free, but it costs a copy on every call.
Most backtracking code instead keeps one mutable list that every frame shares. That avoids the copies, but now each frame has to undo its own change.
def binary_strings_shared(n):
path = []
out = []
def go():
if len(path) == n:
out.append("".join(path))
return
for bit in "01":
path.append(bit)
go()
path.pop()
go()
return out
print(binary_strings_shared(2)) # ['00', '01', '10', '11']The nested function go reads path, out, and n from the enclosing function's scope. All frames of go see the same list objects. The local variable bit belongs to each frame, so each loop keeps its own place.
| Kind of state | Example | Who undoes changes |
|---|---|---|
| Immutable parameter | `prefix` string, an index `i` | Nobody needs to; each frame has its own value |
| Shared mutable object | `path` list, a `used` array, a set | Your code, after each recursive call |
| Shared accumulator | `out` list, a counter declared `nonlocal` | Nobody; it is supposed to keep growing |
A related point: out.append("".join(path)) saves a new string, not the list itself. If you appended path directly, every entry in out would refer to the same list, and that list ends up empty. A later chapter covers copying results in detail.
Recursion Depth Limits
CPython limits how deep the stack can go. The default limit is usually 1000 frames.
import sys
print(sys.getrecursionlimit()) # typically 1000
def depth(n):
return 0 if n == 0 else 1 + depth(n - 1)
print(depth(500)) # 500
try:
depth(100_000)
except RecursionError as e:
print("RecursionError:", e)In backtracking, the stack depth equals the number of choices along one path, not the number of paths. Some typical depths:
| Problem | Maximum depth |
|---|---|
| Subsets or permutations of n items | n + 1 |
| N-Queens on an n by n board | n + 1 (one level per row) |
| Sudoku | at most 82 (one level per empty cell, plus the first call) |
| Word search for a word of length k | k + 1 |
These depths are small, so the limit rarely causes trouble for classic backtracking problems. It does cause trouble when the depth grows with a large input, for example a path search through a grid with 10,000 cells. sys.setrecursionlimit raises Python's counter, but it does not make the interpreter's real stack bigger, so a very high limit can crash the process instead of raising a clean error. For deep searches, a later chapter shows how to replace the call stack with an explicit stack.
Common Errors
- Missing or unreachable base case. If the state never meets the stopping condition, the result is a
RecursionError. Shared state that is never undone is a frequent cause. - Undoing in the wrong place. The undo must run after the recursive call returns, in the same frame that made the change. If you undo before the call, the child never sees the choice.
- Early
returnthat skips the undo. If a frame returns between making a change and undoing it, the shared state stays changed. Put the undo before every return, or put the return after the undo. - Confusing per-frame and shared state. Reassigning a parameter, as in
prefix = prefix + "0", changes only the current frame. Mutating a shared list changes it for every frame.
Exercises
Exercise
What does f(2) print? def f(n): if n == 0: return print("pre", n) f(n - 1) print("post", n)
Show answer
pre 2, pre 1, post 1, post 2, each on its own line. The pre lines run on the way down. The post lines run as the frames are popped, in reverse order.
Exercise
Why does binarystrings never need to undo anything, while binarystrings_shared must call path.pop()?
Show answer
In binarystrings, prefix + "0" creates a new string for the child, and the caller's prefix stays the same. In binarystrings_shared, every frame mutates the same list. Each frame has to remove its own bit before the caller's loop tries the next bit.
Exercise
For binarystringsshared(n), what is the largest number of go frames on the stack at once, and roughly how many calls to go happen in total?
Show answer
The largest number is n + 1 frames, one for each path length from 0 to n. The total number of calls is 2^(n+1) - 1, the number of nodes in a full binary tree of depth n. Stack space is O(n) and time is exponential.