Sub topic 9
Analyzing recursion with recurrence relations
This chapter assumes you can read recursive functions, know how loops map to Big O, and are comfortable with exponents and basic logarithms. Loops can be counted directly. A recursive function calls itself, so its cost is defined in terms of its own cost on smaller inputs. A recurrence relation is an equation that expresses that cost.
From code to recurrence
Let T(n) be the number of steps a function takes on input size n. To write the recurrence, answer three questions:
- How many recursive calls does one call make?
- How large is the input of each of those calls?
- How much work does one call do outside the recursive calls?
Then write T(n) as the sum of the cost of those calls plus the extra work. Add a base case, such as T(1) = O(1).
Three worked examples
Binary search
Binary search discards half of the range and recurses on the other half. It does constant work per step.
def binary_search(sorted_items, target):
lo, hi = 0, len(sorted_items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sorted_items[mid] == target:
return mid
if sorted_items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1The loop version above does the same thing as a recursive version. In recursive form the recurrence is T(n) = T(n/2) + O(1). Halving n repeatedly reaches 1 after about log2(n) steps, so T(n) = O(log n).
Naive Fibonacci
def fib_naive(n):
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)Each call makes two recursive calls, on n - 1 and n - 2, and does constant work besides. The recurrence is T(n) = T(n-1) + T(n-2) + O(1). The input shrinks by only 1 or 2 per call, and the number of calls roughly doubles at each level. This gives exponential growth, bounded by O(2^n).
Merge sort
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 mergedThere are two calls, each on about n/2 items. The merge loop touches each item once, which is O(n) work. The recurrence is T(n) = 2T(n/2) + O(n).
Seeing the recursion tree
A recursion tree draws one node per call and labels each node with the work done in that call. Summing the labels level by level gives the total.
Level 0 does 8 units of work. Level 1 does 4 + 4 = 8, and level 2 does four times 2 = 8. Every level costs about n. The input is halved at each level, so there are about log2(n) levels. The total is n × log n, which is O(n log n). The next chapter covers this unrolling method and the Master Theorem in detail.
Common errors
- Forgetting the non-recursive work. Merge sort and binary search both make a recursive call on half the input. Merge sort does O(n) work per call. Binary search does O(1). That difference separates O(n log n) from O(log n).
- Counting calls but not their size. Two calls on n - 1 (exponential) are very different from two calls on n/2 (n log n).
- Ignoring hidden costs. In
merge_sort, the slicesitems[:mid]anditems[mid:]copy elements. That copying is O(n), so it fits inside the O(n) term. In a function that is meant to be O(log n), slicing would silently add O(n) per call. - Skipping the base case. The base case sets where the recursion stops, which fixes the depth of the tree.
Exercise
A function on a list of size n makes three recursive calls, each on a list of size n/3, and does O(n) work outside the calls. Write its recurrence, and say how much total work each level of the recursion tree does.
Show answer
T(n) = 3T(n/3) + O(n). At level k there are 3^k calls, each of size n/3^k, so each level does 3^k × O(n/3^k) = O(n) work. Every level costs about n, and there are about log3(n) levels. The total is O(n log n).