Sub topic 4
Describing Running Time with Recurrences
This chapter assumes you can trace a recursive function, read Big-O notation, and recognize the divide, conquer, and combine steps from earlier chapters. The goal here is to turn a recursive algorithm into an equation that describes its running time. Solving those equations is the job of the next two chapters, which cover recursion trees and the master theorem.
Why Loops and Recursion Need Different Tools
For an iterative algorithm, you usually count loop iterations and multiply by the cost of each one. A recursive algorithm doesn't fit that pattern, because part of its cost is the cost of calling itself. The running time is defined in terms of itself, and an equation that does this is called a recurrence relation.
A recurrence has two parts:
- A recursive case that expresses T(n), the time on an input of size n, using T at smaller sizes plus the work done outside the recursive calls.
- A base case that gives the cost directly for small n, such as T(1) = O(1).
The Anatomy of a Divide-and-Conquer Recurrence
Most algorithms in this tutorial produce a recurrence of this shape:
T(n) = a · T(n / b) + f(n)
| Symbol | Meaning | Where to find it in the code |
|---|---|---|
| a | Number of recursive calls made by one invocation | Count the calls that actually run, not the calls written in the source |
| n / b | Size of each subproblem | The argument passed to each recursive call |
| f(n) | Work done outside the recursive calls | The divide step plus the combine step, including any copying |
| T(base) | Cost when recursion stops | The base-case branch |
Reading Recurrences Off Real Code
Take merge sort from the earlier chapter. One call on n elements does the following:
- It slices the list into two halves. Python slicing copies, so this costs O(n).
- It makes two recursive calls, each on about n/2 elements.
- It merges the two sorted halves in O(n).
So T(n) = 2T(n/2) + O(n), with T(1) = O(1).
Binary search does constant work to compute mid and compare, then continues on one half. The loop version is equivalent to a recursion that makes one call per step:
T(n) = T(n/2) + O(1)
The number of calls written in the code can differ from the number that actually run. Binary search contains two branches, but only one runs per step, so a = 1. Count the calls executed on a single path through the function.
Floors, Ceilings, and Why We Usually Ignore Them
Merge sort really splits n into ⌊n/2⌋ and ⌈n/2⌉, so the exact recurrence is:
T(n) = T(⌊n/2⌋) + T(⌈n/2⌉) + cn
Analysts usually write 2T(n/2) + cn and assume n is a power of 2. For the recurrences in this tutorial, rounding changes subproblem sizes by at most 1. That shifts the answer by a constant factor at most, and the Big-O class stays the same. You can check this on actual numbers. The program below counts the element moves done by every merge and compares the count with the exact recurrence.
import math
def merge_sort_count(a):
"""Return (sorted list, total elements written by all merges)."""
if len(a) <= 1:
return a, 0
mid = len(a) // 2
left, c_left = merge_sort_count(a[:mid])
right, c_right = merge_sort_count(a[mid:])
out = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out, c_left + c_right + len(out)
def W(n):
"""Exact recurrence: W(n) = W(floor(n/2)) + W(ceil(n/2)) + n, W(1) = 0."""
if n <= 1:
return 0
return W(n // 2) + W(n - n // 2) + n
for n in [8, 64, 100, 512, 1000, 1024]:
data = list(range(n, 0, -1))
_, measured = merge_sort_count(data)
print(f"n={n:5d} measured={measured:6d} W(n)={W(n):6d} "
f"n*log2(n)={n * math.log2(n):9.1f}")The measured count always equals W(n), because the recurrence models exactly what the code does. When n is a power of 2, both equal n log₂ n exactly. For n = 100 and n = 1000 they come out close to n log₂ n but not equal, which shows that floors and ceilings don't change the growth rate.
Recurrences That Don't Fit the Standard Shape
Some algorithms split unevenly or shrink the input by subtraction. Write what the code does and don't force it into a · T(n/b) + f(n).
| Algorithm | Recurrence | Why |
|---|---|---|
| Quicksort, worst case | T(n) = T(n − 1) + O(n) | The pivot is the minimum or maximum, so one side is empty |
| Quicksort, 1/3 to 2/3 split | T(n) = T(n/3) + T(2n/3) + O(n) | The two subproblems have different sizes |
| Naive recursive Fibonacci | T(n) = T(n − 1) + T(n − 2) + O(1) | Subtractive and overlapping subproblems |
| Quickselect, expected | E[T(n)] ≤ E[T(3n/4)] + O(n), roughly | A random pivot lands in the middle half with probability 1/2 |
Subtractive recurrences such as T(n − 1) + O(n) usually lead to polynomial costs like O(n²). Recurrences with two subtractive calls, as in Fibonacci, grow exponentially. The master theorem does not cover either kind, so the recursion-tree method or direct expansion is needed.
A Reference Table for This Tutorial
These are the recurrences of the algorithms covered in later chapters. The solutions are listed for orientation. The next two chapters show how to derive them.
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search | T(n/2) + O(1) | O(log n) |
| Fast exponentiation | T(n/2) + O(1) | O(log n) multiplications |
| Merge sort | 2T(n/2) + O(n) | O(n log n) |
| Counting inversions | 2T(n/2) + O(n) | O(n log n) |
| Maximum subarray | 2T(n/2) + O(n) | O(n log n) |
| Schoolbook split multiplication | 4T(n/2) + O(n) | O(n²) |
| Karatsuba | 3T(n/2) + O(n) | O(n^1.585) |
| Strassen | 7T(n/2) + O(n²) | O(n^2.807) |
Some rows share a recurrence even though the algorithms do different things. Running time depends only on a, b, and f(n). Karatsuba and the schoolbook method differ only in a, and that single change lowers the exponent.
Common Errors
Forgetting hidden linear work
Slicing, list concatenation, and building new lists all cost time proportional to their length. Binary search written with slices looks harmless:
def bs_slice(a, target):
if not a:
return False
mid = len(a) // 2
if a[mid] == target:
return True
if a[mid] < target:
return bs_slice(a[mid + 1:], target)
return bs_slice(a[:mid], target)
print(bs_slice([1, 3, 5, 7, 9], 7)) # TrueEach slice copies about n/2 elements, so the recurrence becomes T(n) = T(n/2) + O(n), which is O(n). That is no faster than a linear scan. Merge sort can afford to slice because its f(n) is already O(n). Binary search can't, because its f(n) is supposed to be O(1).
Confusing a with b
In T(n) = 3T(n/2) + n, there are three calls, each on half the input. Writing 2T(n/3) instead describes a different algorithm with a different answer.
Dropping the base case or making it non-constant
A base case like "if n ≤ 16, use insertion sort" costs O(1) only because 16 is a fixed constant. If the cutoff grows with n, the base-case cost must appear in the analysis.
Measuring the wrong n
For Karatsuba, n is the number of digits or bits, not the numeric value. For fast exponentiation, the recursion shrinks the exponent, so n is the exponent. Choose the quantity that the recursion actually shrinks.
Recurrences for Other Resources
The same technique measures more than time. Recursion depth, which determines stack usage, follows D(n) = D(n/2) + 1 for merge sort, giving O(log n). For worst-case quicksort, D(n) = D(n − 1) + 1, giving O(n). That depth is why naive quicksort can overflow Python's default recursion limit of about 1000 on already-sorted input. The final chapter of this tutorial covers that problem.
Exercise
A function on a list of n elements does an O(n²) loop, then makes three recursive calls, each on n/3 elements, and stops when n ≤ 1. Write its recurrence, including the base case.
Show answer
T(n) = 3T(n/3) + O(n²) for n > 1, and T(n) = O(1) for n ≤ 1. Here a = 3, b = 3, and f(n) = n².
Exercise
Someone rewrites merge sort so that merging is done by calling Python's sorted(left + right) instead of a linear merge. Assume sorted takes O(n log n). What is the new recurrence, and why is it worse than the original?
Show answer
T(n) = 2T(n/2) + O(n log n). The combine step now costs O(n log n) instead of O(n), so f(n) grows faster. It solves to O(n log² n), which is slower than O(n log n). Calling a full sort inside the algorithm also defeats the purpose of writing merge sort.
Exercise
Write the time recurrence and the recursion-depth recurrence for power(x, n) from the fast exponentiation example, measuring n as the exponent and counting multiplications as unit cost.
Show answer
Time: T(n) = T(⌊n/2⌋) + O(1), with T(0) = O(1), because each call makes one recursive call and at most two multiplications. Depth: D(n) = D(⌊n/2⌋) + 1, with D(0) = 1. Both solve to O(log n).