Sub topic 2
From Recursive Code to a Running-Time Recurrence
This chapter assumes you can read recursive functions and know Big-O, Big-Omega, and Big-Theta notation. You don't need any method for solving recurrences yet. The goal here is narrower: given a recursive function, write down a correct recurrence for its running time. Most mistakes in recurrence analysis happen at this step rather than in the solving. If a recurrence leaves out a hidden linear-time copy, the master theorem will give a confident wrong answer.
The Three Questions
Every recursive algorithm can be described by answering three questions about a single call on an input of size n:
- How many recursive calls does it make? Call this count a.
- How big is each subproblem? Often n/b for some constant b > 1. Sometimes it is n − 1 or another uneven size.
- How much work happens outside the recursive calls? This is the divide-and-combine cost f(n). It covers splitting the input, merging results, loops, and copying.
Then add a base case: for inputs below some constant size, the function does constant work. Put together, the answers give a recurrence such as T(n) = aT(n/b) + f(n), with T(n) = Θ(1) for small n.
Worked Example: Merge Sort
def merge_sort(xs):
# T(n) = 2T(n/2) + Theta(n): two half-size calls plus a linear merge
if len(xs) <= 1:
return xs
mid = len(xs) // 2
left = merge_sort(xs[:mid])
right = merge_sort(xs[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]Apply the three questions:
- Calls: two,
merge_sort(xs[:mid])andmerge_sort(xs[mid:]). So a = 2. - Sizes: ⌊n/2⌋ and ⌈n/2⌉. We write both as n/2, so b = 2.
- Outside work: the slices
xs[:mid]andxs[mid:]copy n elements in total, which is Θ(n). The merge loop runs at most n iterations, and the twoextendcalls copy whatever is left over. All of this adds up to Θ(n).
Result: T(n) = 2T(n/2) + Θ(n), with T(1) = Θ(1).
The slicing cost is absorbed here because the merge already costs Θ(n). That won't always be the case, as the binary search example below shows.
Worked Example: Binary Search
def binary_search(xs, target, lo=0, hi=None):
# T(n) = T(n/2) + Theta(1): one half-size call plus constant work
if hi is None:
hi = len(xs)
if lo >= hi:
return -1
mid = (lo + hi) // 2
if xs[mid] == target:
return mid
if xs[mid] < target:
return binary_search(xs, target, mid + 1, hi)
return binary_search(xs, target, lo, mid)
print(binary_search([1, 3, 5, 7, 9, 11], 7)) # 3The function body contains two recursive calls, but at most one runs in any single invocation, because they sit in mutually exclusive branches. So a = 1, not 2. In the worst case the range shrinks to about half, so b = 2. Everything else is comparisons and arithmetic, so f(n) = Θ(1). Here n means the range size hi − lo, not len(xs).
Result: T(n) = T(n/2) + Θ(1).
Hidden Costs: The Slicing Trap
Here is binary search written in a common "Pythonic" style:
def bs_slice(xs, target, cost):
cost[0] += 1 # constant work for this call
if not xs:
return False
mid = len(xs) // 2
if xs[mid] == target:
return True
if xs[mid] < target:
right = xs[mid + 1:]
cost[0] += len(right) # slicing copies len(right) elements
return bs_slice(right, target, cost)
left = xs[:mid]
cost[0] += len(left)
return bs_slice(left, target, cost)
for p in range(10, 21, 5):
n = 2 ** p
cost = [0]
bs_slice(list(range(n)), n, cost) # target larger than every element
print(n, cost[0], round(cost[0] / n, 3))The output ratio stays near 1 as n grows, so the work is linear rather than logarithmic. Each slice copies about half the current list, so the recurrence is T(n) = T(n/2) + Θ(n), which solves to Θ(n). The structure matches the index-based version, but f(n) changed, and f(n) controls the answer.
Python operations that hide linear costs include slicing, list(...), + on lists or strings, in on a list, sum, max, sorted, and copy. When you build f(n), check every line of the non-recursive part for these.
Patterns and Their Recurrences
| Code shape | Recurrence |
|---|---|
| Two half-size calls, linear merge (merge sort) | T(n) = 2T(n/2) + Θ(n) |
| One half-size call, constant work (binary search) | T(n) = T(n/2) + Θ(1) |
| Three half-size multiplications, linear additions (Karatsuba) | T(n) = 3T(n/2) + Θ(n) |
| Eight half-size matrix products, quadratic additions | T(n) = 8T(n/2) + Θ(n²) |
| Recurse on n − 1, constant work (recursive factorial) | T(n) = T(n − 1) + Θ(1) |
| Recurse on n − 1 and n − 2 (naive Fibonacci) | T(n) = T(n − 1) + T(n − 2) + Θ(1) |
| Pivot lands at one end, linear partition (quicksort worst case) | T(n) = T(n − 1) + Θ(n) |
| Loop of n iterations, each calling on n − 1 (generate permutations) | T(n) = nT(n − 1) + Θ(n) |
Only the first four rows fit the form aT(n/b) + f(n) that the master theorem handles. The subtract-one forms need unrolling or characteristic equations, which later chapters cover. In the last row, a = n is not a constant, which also rules out the master theorem.
Edge Cases When Deriving
Data-dependent splits
Quicksort's split depends on the pivot, so it has no single recurrence. Write one recurrence per scenario. The worst case is T(n) = T(n − 1) + Θ(n), the best case is T(n) = 2T(n/2) + Θ(n), and a split that is always at least 1/10 to 9/10 gives T(n) = T(n/10) + T(9n/10) + Θ(n). State which case you are analyzing.
Choosing the size measure
Pick the quantity that actually shrinks. For binary search that is the range length. For recursive exponentiation power(x, k), which squares the result of power(x, k // 2), the size is k, and T(k) = T(k/2) + Θ(1). Arithmetic on large numbers can break the Θ(1) assumption. If you measure in bits, each multiplication costs more as numbers grow.
Memoization changes everything
Naive Fibonacci satisfies T(n) = T(n − 1) + T(n − 2) + Θ(1), which grows exponentially. With a cache, each value is computed once, so the total is Θ(n). A recurrence for running time is only valid when every call actually does its work. Analyze memoized code by counting distinct subproblems times the work per subproblem.
Base cases
Any base case that does constant work on inputs of constant size gives T(n) = Θ(1) for n ≤ n₀. A "base case" that runs insertion sort on 16 elements still costs Θ(1) asymptotically, because 16 is a constant. If the cutoff grows with n, the base case cost is no longer constant and must be accounted for.
Common Errors
- Counting both branches of an
if/elseas separate calls. - Ignoring the cost of slicing, concatenation, or building new lists in f(n).
- Writing T(n/2) when the subproblem is really n − 1. This error turns Θ(n²) into Θ(n log n).
- Measuring n as the original input length when the recursion only narrows indices.
- Forgetting that a loop around a recursive call multiplies the number of calls.
Exercise
A function f(xs) returns immediately if len(xs) <= 1. Otherwise it computes total = sum(xs), then calls f on each of the first, second, and third thirds of xs, using slices. Write its running-time recurrence and identify a, b, and f(n).
Show answer
T(n) = 3T(n/3) + Θ(n). There are three calls, so a = 3. Each call gets n/3 elements, so b = 3. The sum and the three slices each cost Θ(n) in total, so f(n) = Θ(n).
Exercise
The recursive power(x, k) returns 1 when k == 0. Otherwise it computes half = power(x, k // 2) and returns half * half if k is even, or half * half * x if k is odd. Treating multiplication as constant time, write the recurrence in terms of k. What changes if the code instead returns power(x, k // 2) * power(x, k // 2)?
Show answer
With one call stored in half, T(k) = T(k/2) + Θ(1). Calling power twice gives T(k) = 2T(k/2) + Θ(1). The second version does far more work (it solves to Θ(k) rather than Θ(log k)), even though it returns the same value.
Exercise
Why does bs_slice run in linear time while binary_search runs in logarithmic time, when both make one half-size recursive call?
Show answer
Their f(n) terms differ. binary_search passes indices and does Θ(1) work per call, so T(n) = T(n/2) + Θ(1). bs_slice copies half the list on each call, so T(n) = T(n/2) + Θ(n). The copying sums to about n + n/2 + n/4 + ... = Θ(n).