Sub topic 2
From Recursive Code to a Running-Time Recurrence
This chapter assumes you can read recursive Python functions and that you know Big-Theta notation. Here we only turn code into a recurrence. Solving that recurrence comes in later chapters.
The Three Questions
You can write a running-time recurrence for any recursive function by answering three questions:
- How many recursive calls does one invocation make? Call this number
a. - How big is each subproblem? Write its size in terms of
n, for examplen/2orn - 1. - How much work happens outside the recursive calls? Call this
f(n). It covers splitting the input, combining the results, and any loops.
The recurrence is then T(n) = (sum of the costs of the recursive calls) + f(n), together with a base case such as T(1) = Θ(1).
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]Here are the answers to the three questions for merge sort:
| Question | Answer for merge sort |
|---|---|
| Number of calls | 2 |
| Subproblem size | n/2 each |
| Work outside calls | Θ(n): slicing costs Θ(n) and merging costs Θ(n) |
So T(n) = 2T(n/2) + Θ(n), with T(1) = Θ(1).
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 code contains two recursive calls, but only one of them runs on any path through the function. So a = 1. In this setting, n means hi - lo, the size of the range still being searched. The work outside the call is a few comparisons, which is Θ(1). That gives T(n) = T(n/2) + Θ(1).
Common Errors
- Ignoring hidden linear costs. Suppose binary search sliced the list (
xs[mid+1:]) instead of passing indices. Each slice copies Θ(n) elements, so the recurrence becomes T(n) = T(n/2) + Θ(n). That change makes the algorithm asymptotically slower. - Measuring n in the wrong unit. Pick one size measure, such as list length, range width, or number of digits, and use it everywhere in the recurrence.
- Forgetting the base case. Asymptotic solutions rarely depend on its exact value, but the recurrence is incomplete without one.
- Treating sizes like n/3 and 2n/3 as equal. Uneven splits give T(n) = T(n/3) + T(2n/3) + f(n). That is a different shape of recurrence, covered in a later chapter.
Exercise
A function on a list of length n first runs a double loop over all pairs of elements. It then makes three recursive calls, each on a list of length n/2, and returns. Write its running-time recurrence.
Show answer
T(n) = 3T(n/2) + Θ(n^2), with T(1) = Θ(1). There are three calls, each subproblem has size n/2, and the double loop costs Θ(n^2).
Exercise
A recursive function removes the last element of a list of length n, recurses on the remaining n - 1 elements, and then scans the whole list once. What is its recurrence?
Show answer
T(n) = T(n - 1) + Θ(n), with T(1) = Θ(1). There is one call, the subproblem shrinks by one element, and the scan does linear work.