Sub topic 1
Recursion and the Call Stack, Revisited
Backtracking is recursion used with discipline. Before you build search algorithms, you need a clear picture of what happens in memory when a function calls itself. This chapter reviews that picture and points out the one detail that causes most backtracking bugs.
Prerequisites
This chapter assumes you can already:
- Write functions and loops in Python or a similar language
- Write a simple recursive function with a base case
- Use lists, sets, and two-dimensional arrays
- Read Big-O notation
Frames on the Call Stack
The call stack is the region of memory where the runtime keeps track of active function calls. Each call gets a frame. A frame holds that call's parameters, its local variables, and the point to return to when it finishes. A recursive call pushes a new frame on top of the stack. A return pops that frame and resumes the caller exactly where it left off.
The indentation in this trace shows the depth of the stack:
def trace(n, depth=0):
indent = " " * depth
print(f"{indent}enter trace({n})")
if n == 0:
print(f"{indent}base case")
return 0
result = n + trace(n - 1, depth + 1)
print(f"{indent}return {result}")
return result
trace(3)
# enter trace(3)
# enter trace(2)
# enter trace(1)
# enter trace(0)
# base case
# return 1
# return 3
# return 6Every call runs until it reaches the recursive call and then pauses. The work after the recursive call runs only on the way back up. Backtracking relies on that return trip, because it is where the algorithm undoes a choice.
Local Variables Versus Shared Objects
Each frame has its own local variables, so a recursive call cannot overwrite its caller's locals. Mutable objects such as lists, sets, and grids behave differently. When you pass a list to a recursive call, every frame holds a reference to the same list. A change made deep in the recursion is visible in every frame.
def walk(n, shared, depth=0):
local = depth * 10
shared.append(depth)
if depth < n:
walk(n, shared, depth + 1)
print(depth, local, shared)
walk(2, [])
# 2 20 [0, 1, 2]
# 1 10 [0, 1, 2]
# 0 0 [0, 1, 2]Each frame keeps its own local, but all three frames print the same list. Backtracking algorithms usually share one mutable "current path" for speed. That makes them correct only if each frame cleans up its own changes before returning. Later chapters build on this.
Common Errors
| Mistake | Symptom |
|---|---|
| Missing or unreachable base case | `RecursionError: maximum recursion depth exceeded` |
| Expecting a shared list to reset itself between calls | Results contain leftover elements from other branches |
| Ignoring the return value of the recursive call | The answer computed below is lost |
| Using a mutable default argument such as `shared=[]` | State leaks between separate top-level calls |
Exercise
Change walk so that it calls shared.pop() right after the if block and before the print, and remove the local variable from the print. What does walk(2, []) print?
Show answer
It prints "2 [0, 1]", then "1 [0]", then "0 []". Each frame removes the element it appended before printing. When the outermost call finishes, the list is empty again. This undo step on the return trip is the core idea of backtracking.