Sub topic 1
Recurrence Relations: Defining a Function in Terms of Itself
Prerequisites
This chapter assumes you know Big-O, Big-Omega, and Big-Theta notation. It also assumes you can read recursive functions, use logarithm identities, sum geometric and arithmetic series, and write proofs by induction.
What a Recurrence Is
A recurrence relation defines a function using its own values on smaller inputs. It also needs a base case, such as T(1) = 1. Without a base case, the definition never bottoms out.
From Code to Recurrence
To get a recurrence from code, count two things. First, count the recursive calls and the input size of each one. Second, count the work done outside those calls. Recursive binary search makes one call on half the range and otherwise does constant work, so T(n) = T(n/2) + Θ(1). Merge sort makes two half-size calls and then merges in linear time, so T(n) = 2T(n/2) + Θ(n).
Solving by Unrolling
Unrolling means substituting the recurrence into itself until you can see a pattern. For binary search:
T(n) = T(n/2) + 1 = T(n/4) + 2 = … = T(n/2^k) + k.
The input reaches size 1 when k = log₂ n. That gives T(n) = log₂ n + T(1) = Θ(log n).
Recursion Trees
A recursion tree draws each call as a node and labels the node with its non-recursive work. For merge sort, level i has 2^i nodes, and each node does n/2^i work. So every level costs n in total. The tree has log₂ n + 1 levels, which suggests Θ(n log n).
The code below evaluates the recurrence exactly. The printed ratio T(n) / (n log n) moves toward 1, which matches the guess.
import math
def T(n):
# Merge sort's recurrence with T(1) = 1 and f(n) = n
return 1 if n <= 1 else 2 * T(n // 2) + n
for p in range(4, 21, 4):
n = 2 ** p
print(n, T(n), round(T(n) / (n * math.log2(n)), 4))The Substitution Method
The substitution method proves a guessed bound by induction. Guess T(n) ≤ c·n log₂ n, and assume the bound holds for n/2. Then:
T(n) ≤ 2c(n/2)log₂(n/2) + n = c·n log₂ n − cn + n ≤ c·n log₂ n whenever c ≥ 1.
For the base case n = 2, T(2) = 4 ≤ c·2·1 holds when c = 2.
Exercise
Unroll T(n) = T(n-1) + n with T(1) = 1 and give a Theta bound.
Show answer
T(n) = n + (n-1) + … + 2 + 1 = n(n+1)/2, so T(n) = Θ(n²).