Sub topic 7
Multiple Recursion and Repeated Work
This chapter assumes you can write a recursive function with a base case and a recursive case, and that you know how each call gets its own stack frame. It also assumes you can read simple Big-O notation such as O(n) and O(2^n).
So far, most recursive functions in this tutorial have made one recursive call per invocation. Factorial calls itself once, and so does a function that walks down a linked list. That shape is called linear recursion. The calls form a single chain, and the chain is as long as the recursion is deep.
Multiple recursion (also called tree recursion) is when one invocation makes two or more recursive calls. The calls no longer form a chain. They branch, and the full set of calls forms a tree. This shape fits many problems well, but it brings a cost that linear recursion does not have: the same subproblem can be solved many times over.
The Shape of a Call Tree
The Fibonacci sequence is the standard example. Each number is the sum of the two before it, with fib(0) = 0 and fib(1) = 1.
def fib_naive(n):
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
print(fib_naive(20)) # 6765The code mirrors the mathematical definition exactly, and that is its appeal. Now look at what happens when you call fib_naive(4).
There are nine calls in total. fib(2) is computed twice, and fib(1) is computed three times. Each duplicate is a full, independent call. Python does not notice that it has seen the argument before.
Overlapping Subproblems
A subproblem is a smaller instance of the problem that a recursive call solves. Subproblems overlap when different branches of the call tree ask for the same smaller instance. Fibonacci has heavy overlap because fib(n - 1) itself calls fib(n - 2), which the parent was about to compute anyway.
You can measure the overlap by counting how often each argument shows up:
from collections import Counter
seen = Counter()
def fib_traced(n):
seen[n] += 1
if n < 2:
return n
return fib_traced(n - 1) + fib_traced(n - 2)
fib_traced(6)
for k in sorted(seen, reverse=True):
print(k, seen[k])
print("total calls:", sum(seen.values()))Output:
6 1
5 1
4 2
3 3
2 5
1 8
0 5
total calls: 25The counts for arguments 6 down to 1 are 1, 1, 2, 3, 5, 8. These are Fibonacci numbers themselves. The repeated work grows at the same rate as the answer. Only 7 distinct arguments exist (0 through 6), but the function makes 25 calls.
That gap between distinct arguments and total calls is the most reliable sign of overlap. If a function can only ever receive a small number of different inputs but makes far more calls than that, it is recomputing results.
How Fast the Work Grows
Counting calls for larger inputs shows the problem clearly. The exact count for fib_naive(n) is 2 * fib(n + 1) - 1.
calls = 0
def fib_counted(n):
global calls
calls += 1
if n < 2:
return n
return fib_counted(n - 1) + fib_counted(n - 2)
for n in (10, 20, 30):
calls = 0
fib_counted(n)
print(n, calls)| n | Result `fib(n)` | Calls made by `fib_naive(n)` |
|---|---|---|
| 5 | 5 | 15 |
| 10 | 55 | 177 |
| 20 | 6,765 | 21,891 |
| 30 | 832,040 | 2,692,537 |
| 40 | 102,334,155 | 331,160,281 |
Each step up in n multiplies the work by about 1.618, the golden ratio. The running time is therefore O(φ^n), which is exponential. People often round this to O(2^n) as a loose upper bound. On a typical machine, fib_naive(30) takes a noticeable fraction of a second, and fib_naive(40) takes from tens of seconds to a few minutes in CPython.
Depth Versus Total Calls
Two different numbers describe a call tree, and they are easy to confuse.
- Depth is the longest path from the root to a leaf. It decides how many stack frames exist at the same time, so it decides stack memory use and whether you hit a
RecursionError. - Total calls is the number of nodes in the tree. It decides running time.
For fib_naive(n) the depth is only about n, because the leftmost path goes n, n-1, n-2, ..., 1. The tree is wide, not deep. When the right branch fib(n - 2) runs, the frames of the finished left branch have already been popped.
This also means fixing the depth problem and fixing the time problem need different tools. Raising the recursion limit does nothing for fib_naive. Removing the repeated work does.
Not All Multiple Recursion Is Wasteful
Branching alone does not cause waste. Overlap does. Many tree-recursive algorithms split a problem into disjoint pieces, and every call does useful, unique work.
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
print(merge_sort([5, 2, 9, 1, 5, 6])) # [1, 2, 5, 5, 6, 9]Merge sort makes two recursive calls, but the left half and right half never share elements. No subproblem is solved twice. The total work is O(n log n) and the depth is O(log n). Walking a binary tree works the same way: each node is visited exactly once, because the left and right subtrees are disjoint.
| Algorithm | Calls per invocation | Subproblems overlap? | Total work | Depth |
|---|---|---|---|---|
| Factorial | 1 | No | O(n) | O(n) |
| Binary tree traversal | 2 | No | O(number of nodes) | O(tree height) |
| Merge sort | 2 | No | O(n log n) | O(log n) |
| Naive Fibonacci | 2 | Yes | O(φ^n) | O(n) |
| Naive grid path count | 2 | Yes | Exponential | O(rows + cols) |
The question to ask is whether the subproblems split the input into separate parts or shrink it along paths that can meet again.
A Second Overlapping Example: Grid Paths
Count the paths from the top-left to the bottom-right of a grid when you can only move right or down. To finish at a point that is r rows and c columns away, your last move came from either one row up or one column left.
def grid_paths(r, c):
if r == 0 or c == 0:
return 1
return grid_paths(r - 1, c) + grid_paths(r, c - 1)
print(grid_paths(2, 2)) # 6
print(grid_paths(10, 10)) # 184756The two branches meet again. Going up then left reaches (r - 1, c - 1), and so does going left then up. Only (r + 1) * (c + 1) distinct argument pairs exist, which is 121 for a 10 by 10 grid, yet grid_paths(10, 10) makes several hundred thousand calls. The same check applies: few distinct inputs, many calls.
Common Errors
- Assuming the recursive version is efficient because it is short. Code length says nothing about the size of the call tree. Count calls on a small input before trusting a tree-recursive function on a large one.
- Blaming the recursion limit. As shown above, a slow tree-recursive function is usually exponential, not deep.
sys.setrecursionlimitwill not help. - Weak base cases.
fib_naive(-3)returns-3silently, becausen < 2also catches negative numbers. A base case that is too broad hides bad input. A base case that is too narrow, such as checking onlyn == 0, makesfib_naive(1)callfib_naive(-1)and recurse until it raisesRecursionError. Validate inputs at the entry point if negative values are possible. - Global counters left dirty. When you instrument a function with a global counter, as
fib_counteddoes, reset it before each measurement or the numbers pile up.
Where This Leads
Overlap is a problem and also an opportunity. Because the same subproblems recur, you can store each answer the first time it is computed and reuse it after that. You can also compute the answers in order from the smallest upward with a loop. A later chapter, "Memoization and Bottom-Up Iteration," covers both techniques. The next chapter, "Comparing Time and Space Costs," puts numbers on the trade-offs between these shapes and their iterative equivalents.
Exercise
How many calls does fibnaive(7) make in total, and how many times is fibnaive(2) called during it?
Show answer
Total calls are 2 fib(8) - 1 = 2 21 - 1 = 41. The argument 2 is reached fib(7 - 2 + 1) = fib(6) = 8 times. You can confirm both numbers with fib_traced(7).
Exercise
A tribonacci function is defined as trib(n) = trib(n-1) + trib(n-2) + trib(n-3), with trib(0) = trib(1) = 0 and trib(2) = 1. Written naively, do its subproblems overlap, and is it likely to fail by RecursionError or by slowness for n = 35?
Show answer
The subproblems overlap heavily. trib(n-1) itself calls trib(n-2) and trib(n-3), which the parent also calls directly. Its depth is only about n, so 35 frames is well under CPython's limit of 1000. It fails by slowness: the call count grows by a factor of about 1.84 per step, which is tens of millions of calls at n = 35.
Exercise
Binary search on a sorted list makes at most one recursive call per invocation, and merge sort makes two. Explain why neither one has overlapping subproblems, using the "distinct arguments versus total calls" test.
Show answer
In binary search, each call works on a strictly smaller range that is never revisited, so it makes O(log n) calls, each on a distinct range. In merge sort, the two halves are disjoint slices, and every call works on a different, unique sub-range of the original list. Merge sort makes about 2n - 1 calls, one for each distinct sub-range it creates. In both cases the number of calls equals the number of distinct subproblems, so no work is repeated.