Sub topic 9
Analyzing recursion with recurrence relations
This chapter assumes you can read and write recursive functions and that you know the Big O simplification rules (drop constants and lower-order terms) from earlier chapters. You should also be comfortable with exponents and a basic idea of logarithms. Loops can be analyzed by counting iterations. Recursion needs a different tool, because the function's cost is defined in terms of its own cost on smaller inputs.
Why loop counting is not enough
In a loop, you multiply the iteration count by the cost of the body. A recursive function has no visible iteration count. Its running time on input size n depends on its running time on smaller inputs.
A recurrence relation is an equation that expresses the cost T(n) of a function in terms of T evaluated at smaller sizes, plus the work done outside the recursive calls. Writing the recurrence is the analysis step. Solving it (covered in the next chapter) is a separate step.
Building a recurrence in three steps
For any recursive function, answer three questions:
- Base case. What is
Tfor the smallest inputs? This is usually a constant, writtenT(1) = corT(0) = c. - Recursive calls. How many calls does one invocation make, and how large is the input to each?
- Local work. How much work does one invocation do besides the recursive calls? This includes loops, slicing, copying, and merging.
The recurrence is the sum: T(n) = (cost of each recursive call) + (local work).
Example: linear recursion
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)The base case costs a constant. Each call makes one recursive call on n - 1 and does one multiplication.
T(n) = T(n - 1) + c, with T(1) = c.
Unrolling gives T(n) = c + c + ... + c, which is n terms, so T(n) = O(n).
Example: halving the input
A recursive binary search looks at the middle element, then recurses on one half.
def bsearch(items, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
return bsearch(items, target, mid + 1, hi)
return bsearch(items, target, lo, mid - 1)One call, half the range, constant local work:
T(n) = T(n / 2) + c
Halving n until it reaches 1 takes about log2(n) steps, and each step costs c, so T(n) = O(log n).
Example: two calls on halves
merge_sort from the code examples makes two calls on halves and then merges in a linear pass:
T(n) = 2T(n / 2) + cn
The cn term is the merge loop plus the slices items[:mid] and items[mid:], which each copy about n / 2 elements. This solves to O(n log n).
Example: two calls on almost the same size
fib_naive calls itself on n - 1 and n - 2:
T(n) = T(n - 1) + T(n - 2) + c
The input shrinks by a small amount while the number of calls doubles, so the cost grows exponentially. The usual upper bound is O(2^n). The tight bound is smaller, about 1.618^n (the golden ratio raised to n), but O(2^n) is correct as an upper bound.
Summary table
| Function | Recurrence | Result |
|---|---|---|
| `factorial(n)` | `T(n) = T(n-1) + c` | `O(n)` |
| recursive binary search | `T(n) = T(n/2) + c` | `O(log n)` |
| `merge_sort` | `T(n) = 2T(n/2) + cn` | `O(n log n)` |
| `fib_naive` | `T(n) = T(n-1) + T(n-2) + c` | `O(2^n)` |
| sum with slicing (below) | `T(n) = T(n-1) + cn` | `O(n^2)` |
Seeing the recursion tree
A recursion tree draws every call as a node and labels each node with its local work. Summing the labels level by level often gives the answer without algebra.
For merge sort, the tree looks like this:
Read the tree in three parts:
- Work per level. Level 0 has one node doing
n. Level 1 has two nodes doingn / 2each, a total ofn. Level 2 has four nodes doingn / 4each, againn. Every level costs aboutn. - Number of levels. The size reaches 1 after about
log2(n)halvings, so there are aboutlog2(n) + 1levels. - Total.
nper level timeslog2(n) + 1levels givesO(n log n).
This level-by-level view is the idea behind the Master Theorem, which the next chapter covers.
Checking a recurrence by running code
A recurrence is a claim about counts. You can test it by instrumenting the code. The program below counts calls for fib_naive and counts elements copied by a slicing-based sum.
def fib_calls(n):
"""Return (fib(n), number of calls made)."""
if n < 2:
return n, 1
a, calls_a = fib_calls(n - 1)
b, calls_b = fib_calls(n - 2)
return a + b, calls_a + calls_b + 1
def sum_slice(items, stats):
if not items:
return 0
stats["copied"] += len(items) - 1 # cost of items[1:]
return items[0] + sum_slice(items[1:], stats)
for n in (5, 10, 20):
value, calls = fib_calls(n)
print("fib", n, "=", value, "calls:", calls)
for n in (10, 100, 200):
stats = {"copied": 0}
sum_slice(list(range(n)), stats)
print("sum_slice", n, "copied:", stats["copied"], "n(n-1)/2 =", n * (n - 1) // 2)The output shows 15, 177, and 21891 calls for n = 5, 10, 20. Each call count is 2·F(n+1) − 1, where F is the Fibonacci sequence, so the count grows by about 1.6 times when n goes up by 1. The slicing sum copies exactly n(n-1)/2 elements, which matches T(n) = T(n-1) + cn and shows it is quadratic even though it looks like a single recursive call.
Hidden local work
The most common mistake is to treat the local work as constant when it is not. Slicing a list, concatenating strings, and copying a collection all cost time proportional to the size copied.
def sum_slice_wrong_cost(items):
if not items:
return 0
return items[0] + sum_slice_wrong_cost(items[1:]) # slice is O(n), not O(1)The shape T(n) = T(n - 1) + c suggests O(n). The slice makes the real recurrence T(n) = T(n - 1) + cn, which is O(n^2). Passing indices instead of slices, as bsearch does with lo and hi, restores constant local work.
Other common errors
- Forgetting the base case. A recurrence without
T(1) = chas no end. The base-case constant rarely changes the Big O, but it must exist. - Miscounting the calls. Two calls that each take half the input give
2T(n/2). One call on half givesT(n/2). Binary search and merge sort differ by exactly this factor, and it changes the answer fromO(log n)toO(n log n), together with the linear merge. - Counting the same call twice. In
fib_memo, the second call for a givennreturns immediately from the dictionary. The recurrence for the first computation of each value isT(n) = T(n-1) + c, since then - 2branch hits the memo. This givesO(n). - Mixing the input size with the input value. For
factorial(n),nis a number, and the cost isO(n)in the value ofn. If the input is a list,nshould be the list length. State clearly whatnmeasures. - Assuming a bound is tight.
O(2^n)forfib_naiveis a valid upper bound, but it is not the tightest one. Be explicit about whether you want an upper bound or a tight bound.
Recurrences with unequal splits
Not every divide-and-conquer function splits evenly. A quicksort with a poor pivot gives T(n) = T(n - 1) + cn, which is O(n^2). With a balanced pivot it gives T(n) = 2T(n/2) + cn, which is O(n log n). The recurrence depends on the input, which connects to the best, worst, and average case discussion from the previous chapter. You write one recurrence per case.
What to carry forward
- A recurrence has three parts: base case, recursive calls with their input sizes, and local work.
- Write the recurrence first and solve it second.
- A recursion tree shows work per level and the number of levels, and their product is the total.
- Verify a recurrence by counting calls or operations on a few input sizes.
- Hidden costs such as slicing change the recurrence and the final bound.
Exercise
Write the recurrence for the function below and state its time complexity. def countdown(items): if len(items) <= 1: return 0 return 1 + countdown(items[:len(items) // 2]) + count_down(items[len(items) // 2:])
Show answer
There are two calls, each on half the list. The local work is two slices that copy about n/2 elements each, so about n elements in total. The recurrence is T(n) = 2T(n/2) + cn, with T(1) = c. Every level of the recursion tree does about cn work and there are about log2(n) + 1 levels, so T(n) = O(n log n). The same shape as merge_sort.
Exercise
A function on a list of n items makes one recursive call on the list without its first element, using a slice, and then does a loop over all n items. What is the recurrence and the complexity?
Show answer
T(n) = T(n - 1) + cn, because the slice costs about n and the loop costs n. Unrolling gives cn + c(n-1) + ... + c, which is about c·n(n+1)/2, so the complexity is O(n^2).
Exercise
fibmemo computes fib(n) with a dictionary. Why is its time O(n) when fibnaive is O(2^n), even though both contain two recursive calls?
Show answer
In fibmemo, each value from 0 to n is computed at most once and stored. The second recursive call at each level finds its result in the memo and returns in constant time. That gives about n computations with constant work each, so O(n) time (and O(n) space for the memo and the call stack). fibnaive recomputes the same subproblems many times, so its call count grows exponentially.