Sub topic 16
Analyzing Recursive Algorithms with Recurrence Relations
This chapter assumes you can read Python, know Big-O notation (O(n), O(n²), O(log n)), and have worked through the earlier chapters on tree recursion, memoization, and merge sort. The aim is to estimate two costs of any recursive function before you run it on large inputs: how much time it takes and how much stack space it uses.
What a Recurrence Relation Is
A recurrence relation describes the cost of a problem of size n in terms of the cost of smaller problems. You read it straight off the code. Each recursive call becomes a term T(smaller size). The work the function does itself, outside its recursive calls, becomes an extra term.
Take factorial:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)Each call does a constant amount of work: one comparison and one multiplication. It then makes one call on n − 1. The recurrence is:
- T(0) = O(1)
- T(n) = T(n − 1) + O(1)
Unrolling it gives T(n) = O(1) + O(1) + ... with n + 1 terms, so T(n) = O(n).
To write a recurrence, answer three questions about the function:
- How many recursive calls does one call make?
- How big is each subproblem?
- How much work does the call do apart from those recursive calls?
The Recursion Tree Method
The most reliable way to solve a recurrence by hand is to draw the recursion tree. Each node is one call, and you label it with the non-recursive work that call does. You then add up the labels, usually one level at a time.
Merge sort has the recurrence T(n) = 2T(n/2) + O(n). It makes two calls on halves, and merging costs time proportional to n.
At level k there are 2^k calls, each on n/2^k items, so every level does n work in total. The size halves at each level until it reaches 1, which takes log₂ n levels. Total time is n × log₂ n = O(n log n).
Naive Fibonacci has a different shape: T(n) = T(n − 1) + T(n − 2) + O(1). Each node does constant work, so the total cost is the number of nodes. The tree is unbalanced, but it still roughly multiplies by the golden ratio φ ≈ 1.618 at each level. That makes T(n) = O(φⁿ), which is exponential.
Checking Your Analysis by Counting Calls
You can test a recurrence by counting calls. If the analysis says the cost grows by a factor of φ for each step of n, then increasing n by 5 should multiply the call count by about φ⁵ ≈ 11.
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
for n in [10, 15, 20, 25]:
calls = 0
fib(n)
print(n, calls)
# 10 177
# 15 1973
# 20 21891
# 25 242785Each row is about 11 times the one before, which matches the analysis. Now compare the memoized version from the memoization chapter. With lru_cache, each fib(k) for k from 0 to n does its own work exactly once. Every later request for fib(k) is a cache hit that costs O(1). That gives n + 1 distinct calls at O(1) each, so the cost is O(n). Memoization turns the recurrence into "number of distinct subproblems × work per subproblem".
A Common Trap: Hidden Work in Each Call
The "work apart from recursive calls" term is where most analyses go wrong. Look at the list sum from the lists chapter:
def total(items):
if not items:
return 0
return items[0] + total(items[1:])It looks like T(n) = T(n − 1) + O(1), but items[1:] copies n − 1 elements. The real recurrence is T(n) = T(n − 1) + O(n), which adds up to n + (n − 1) + ... + 1 = O(n²). Passing an index avoids the copy:
def total_from(items, i=0):
if i == len(items):
return 0
return items[i] + total_from(items, i + 1)
print(total_from([3, 1, 4])) # 8The fixed version satisfies T(n) = T(n − 1) + O(1), which is O(n).
Common Recurrences and Their Solutions
| Recurrence | Example | Time | Max stack depth |
|---|---|---|---|
| T(n) = T(n−1) + O(1) | factorial, `total_from` | O(n) | O(n) |
| T(n) = T(n−1) + O(n) | `total` with slicing | O(n²) | O(n) |
| T(n) = T(n/2) + O(1) | binary search | O(log n) | O(log n) |
| T(n) = 2T(n/2) + O(1) | tree height on a balanced tree | O(n) | O(log n) |
| T(n) = 2T(n/2) + O(n) | merge sort | O(n log n) | O(log n) |
| T(n) = T(n−1) + T(n−2) + O(1) | naive Fibonacci | O(φⁿ) | O(n) |
| T(n) = n·T(n−1) + O(n) | generating permutations | O(n · n!) | O(n) |
For divide-and-conquer recurrences of the form T(n) = a·T(n/b) + O(n^d), the master theorem gives the answer by comparing d with log_b a:
- If d > log_b a, the top-level work dominates: O(n^d).
- If d = log_b a, every level costs about the same: O(n^d log n).
- If d < logb a, the leaves dominate: O(n^(logb a)).
For merge sort, a = 2, b = 2, d = 1, and log₂ 2 = 1. The two sides are equal, so the cost is O(n log n). For binary search, a = 1, b = 2, d = 0, and log₂ 1 = 0. They are equal again, so the cost is O(log n). The master theorem only applies when the subproblems shrink by a constant factor. It does not cover T(n − 1) recurrences.
Stack Space Is a Separate Question
Time counts every node in the recursion tree. Stack space counts only the longest path from the root to a leaf, because only one chain of frames is live at any moment. When a call returns, its frame is popped and the space is reused.
For this reason, naive Fibonacci takes exponential time but its stack depth is only O(n): the deepest chain is fib(n) → fib(n−1) → ... → fib(1). Merge sort reaches a depth of only O(log n), so it never hits Python's recursion limit in practice. It still uses O(n) extra heap memory for the merged lists. Factorial and total_from reach depth n. That depth explains why they fail with RecursionError around n = 1000 in CPython, as the stack-depth chapter showed.
For unbalanced data, the depth depends on the input's shape. Tree height on a balanced tree has depth O(log n). On a degenerate tree, where each node has only one child, the depth is O(n), which is the case that calls for an explicit stack.
Common Errors
- Treating slices and concatenations as O(1).
- Assuming two recursive calls mean O(2ⁿ). Two calls on halves give O(n) or O(n log n). Two calls on n − 1 and n − 2 give exponential time.
- Forgetting that memoization changes the count of distinct calls, not the recurrence's shape.
- Reporting time complexity when the real risk is stack depth.
Exercise
Write the recurrence for this function, then give its time and maximum stack depth. def count(lo, hi): return 0 if lo >= hi else 1 + count(lo, (lo + hi) // 2) + count((lo + hi) // 2 + 1, hi)
Show answer
Each call does O(1) work and makes two calls on halves: T(n) = 2T(n/2) + O(1). By the master theorem, a = 2, b = 2, d = 0, and 0 < log₂ 2 = 1, so the time is O(n^1) = O(n). The range halves each level, so the stack depth is O(log n).
Exercise
The string reverse function reverse(s) returns reverse(s[1:]) + s[0]. Give its recurrence and time complexity, and explain why.
Show answer
T(n) = T(n − 1) + O(n), because both the slice s[1:] and the concatenation copy about n characters. Summing n + (n − 1) + ... + 1 gives O(n²) time. The stack depth is O(n).
Exercise
The memoized fib(n) and the naive fib(n) both have stack depth O(n). Why does only the time complexity change?
Show answer
Memoization prunes repeated subtrees, so the total number of nodes in the recursion tree drops from O(φⁿ) to O(n). The first call fib(n) → fib(n−1) → ... → fib(1) still forms a chain of n live frames before any cache hits occur, so the longest path, and therefore the stack depth, stays O(n).