Lesson 5 · Foundations

Recurrence Relations

A recurrence relation defines a function in terms of its value on smaller inputs. Recursive algorithms are analysed by writing their running time as a recurrence and then solving it for a closed form.

Recurrence Relations concept diagramThe recurrence T(n) = a·T(n/b) + f(n), with a marked as the number of subproblems, n/b as the size of each, and f(n) as the work to divide and combine. Below, a problem of size n is divided into a subproblems of size n/b, each solved recursively, and their answers are combined at cost f(n). Examples: merge sort has a = 2, b = 2, f(n) = n; binary search has a = 1, b = 2, f(n) = 1.T(n)=a· T(n/b)+f(n)anumber of subproblemsn/bsize of each onef(n)divide + combine workproblemsize nsubproblem n/b⋮ a calls ⋮subproblem n/bcombinecosts f(n)divideconquer: each solved recursively, costing T(n/b)= T(n)merge sort: a = 2, b = 2, f(n) = nbinary search: a = 1, b = 2, f(n) = 1
1

A Function Defined by Itself

  1. Base case – the value for the smallest input, e.g. T(1) = 1.
  2. Recursive case – the value for n in terms of smaller inputs, e.g. T(n) = 2T(n/2) + n.
  3. Closed form – an expression in n alone, e.g. T(n) = n log₂ n + n.
  4. Asymptotic bound – the growth rate you report, e.g. Θ(n log n).

A recurrence relation is an equation that defines a function, or the terms of a sequence, using its own values on smaller inputs. It has two parts: a base case, which gives the value directly for the smallest inputs, and a recursive case, which expresses the value for larger inputs in terms of smaller ones.

In the design and analysis of algorithms (DAA), recurrences describe the running time of recursive algorithms. Merge sort splits an array into two halves, sorts each recursively and merges them in linear time, so the recurrence relation of merge sort is T(n) = 2T(n/2) + n with T(1) = 1. Solving the recurrence means finding a closed form, here Θ(n log n), that no longer refers to T itself.

  • Divide-and-conquer form: T(n) = a·T(n/b) + f(n), shown in the diagram
  • Subtract-and-conquer form: T(n) = T(n − 1) + f(n)
  • Mathematical sequences: Fibonacci F(n) = F(n − 1) + F(n − 2), F(0) = 0, F(1) = 1
2

Writing the Recurrence from Code

Read the recursive function and account for everything one call does. The number of recursive calls becomes the coefficient, the size passed to each call becomes the argument of T, and all the work outside the recursive calls becomes the added term. The base case of the code gives the base case of the recurrence.

Binary search, for example, compares with the middle element (constant work) and recurses on one half, so T(n) = T(n/2) + c. Quick sort partitions in linear time and recurses on both parts; if the pivot always splits evenly it is T(n) = 2T(n/2) + n, and if it always splits off one element it degrades to T(n) = T(n − 1) + n.

Recurrence relations of common algorithms
AlgorithmRecurrenceSolution
Binary searchT(n) = T(n/2) + 1Θ(log n)
Merge sortT(n) = 2T(n/2) + nΘ(n log n)
Quick sort, best caseT(n) = 2T(n/2) + nΘ(n log n)
Quick sort, worst caseT(n) = T(n − 1) + nΘ(n²)
Factorial (recursive)T(n) = T(n − 1) + 1Θ(n)
Binary tree traversalT(n) = 2T(n/2) + 1Θ(n)
Tower of HanoiT(n) = 2T(n − 1) + 1Θ(2ⁿ)
Naive FibonacciT(n) = T(n − 1) + T(n − 2) + 1Θ(φⁿ), φ ≈ 1.618
Strassen's matrix multiplicationT(n) = 7T(n/2) + n²Θ(n^2.81)
  • Two calls on the same half still count twice: the coefficient is calls made, not distinct subproblems
  • Uneven splits give uneven terms, e.g. T(n) = T(n/3) + T(2n/3) + n, which still solves to Θ(n log n)
  • Floors and ceilings (n/2 rounded) do not change the asymptotic answer, so they are usually dropped
3

Choosing a Solving Method

There are four standard methods for algorithm recurrences, plus the characteristic equation for linear recurrences in discrete mathematics. Choose by the form of the recurrence: the master theorem is fastest when it applies, and the others work when it does not. The tracer below solves four recurrences with the recursion-tree method and checks each against the master theorem.

Which method to use
MethodIdeaBest for
Substitutionguess the bound, then prove it by inductionconfirming a guess; any form
Iteration (back-substitution)expand T repeatedly until the base case, then sumT(n − 1) forms and simple divisions
Recursion treedraw the calls as a tree, sum the work level by levelbuilding intuition and making a guess
Master theoremcompare f(n) with n^(log_b a)T(n) = aT(n/b) + f(n)
Characteristic equationsolve a polynomial whose roots give the closed formlinear recurrences like Fibonacci
  • The master theorem cannot solve T(n) = T(n − 1) + n; iteration can
  • Always check the answer against a few small values, as the tracer does at n = 16
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Recurrence relationAn equation defining T(n) in terms of T on smaller inputs.
  • Base caseThe value given directly for the smallest inputs.
  • Closed formAn expression for T(n) that does not refer to T.
  • Recursion treeThe calls drawn as a tree, labelled with the work each does.

Formulas

  • Divide and conquerT(n) = a·T(n/b) + f(n)
  • Leaves of the treea^(log_b n) = n^(log_b a)
  • Master theoremcompare f(n) with n^(log_b a): smaller, equal or larger
  • Characteristic equationaₙ = c₁aₙ₋₁ + c₂aₙ₋₂ → r² = c₁r + c₂
Implementation

Code in Python, C++ and Java

def solve(a, b, k, n):
    # T(n) = a*T(n/b) + n^k, with T(1) = 1, evaluated by direct recursion.
    if n == 1:
        return 1
    return a * solve(a, b, k, n // b) + n**k


def level_sums(a, b, k, n):
    # Work on each level of the recursion tree: nodes on the level * cost per node.
    sums, nodes, size = [], 1, n
    while size > 1:
        sums.append(nodes * size**k)
        nodes, size = nodes * a, size // b
    return sums + [nodes]  # the leaves, T(1) = 1 each


def power(e):
    return "n" if e == 1 else f"n^{e}"


def master(a, b, k):
    # Compare a with b^k, i.e. n^(log_b a) with f(n) = n^k.
    if a < b**k:
        return f"case 3, the root dominates: Theta({power(k)})"
    if a == b**k:
        return f"case 2, every level equal: Theta({power(k)} log n)"
    e = 0
    while b**e < a:
        e += 1
    crit = power(e) if b**e == a else f"n^(log_{b} {a})"
    return f"case 1, the leaves dominate: Theta({crit})"


n = 16
for a, b, k in [(2, 2, 1), (2, 2, 2), (4, 2, 1)]:
    sums = level_sums(a, b, k, n)
    print(f"T(n) = {a}T(n/{b}) + {power(k)}: T({n}) = {solve(a, b, k, n)}")
    print(f"  level sums {' + '.join(map(str, sums))} = {sum(sums)}")
    print(f"  master theorem: {master(a, b, k)}")

# T(n) = T(n-1) + n is not of the form a*T(n/b) + f(n): unroll it instead.
t = 1
for m in range(2, n + 1):
    t += m
print(f"T(n) = T(n-1) + n: T({n}) = {t} = n(n+1)/2 = {n * (n + 1) // 2}")
print("  master theorem does not apply: Theta(n^2) by iteration")
#include <cstdio>
#include <string>
#include <vector>
using namespace std;

long long ipow(long long base, int e) {
    long long r = 1;
    while (e-- > 0) r *= base;
    return r;
}

// T(n) = a*T(n/b) + n^k, with T(1) = 1, evaluated by direct recursion.
long long solve(int a, int b, int k, long long n) {
    if (n == 1) return 1;
    return a * solve(a, b, k, n / b) + ipow(n, k);
}

// Work on each level of the recursion tree: nodes on the level * cost per node.
vector<long long> levelSums(int a, int b, int k, long long n) {
    vector<long long> sums;
    long long nodes = 1, size = n;
    while (size > 1) {
        sums.push_back(nodes * ipow(size, k));
        nodes *= a;
        size /= b;
    }
    sums.push_back(nodes);  // the leaves, T(1) = 1 each
    return sums;
}

string power(int e) { return e == 1 ? "n" : "n^" + to_string(e); }

// Compare a with b^k, i.e. n^(log_b a) with f(n) = n^k.
string master(int a, int b, int k) {
    if (a < ipow(b, k)) return "case 3, the root dominates: Theta(" + power(k) + ")";
    if (a == ipow(b, k)) return "case 2, every level equal: Theta(" + power(k) + " log n)";
    int e = 0;
    while (ipow(b, e) < a) e++;
    string crit = ipow(b, e) == a ? power(e) : "n^(log_" + to_string(b) + " " + to_string(a) + ")";
    return "case 1, the leaves dominate: Theta(" + crit + ")";
}

int main() {
    const long long n = 16;
    int params[3][3] = {{2, 2, 1}, {2, 2, 2}, {4, 2, 1}};
    for (auto& p : params) {
        int a = p[0], b = p[1], k = p[2];
        vector<long long> sums = levelSums(a, b, k, n);
        printf("T(n) = %dT(n/%d) + %s: T(%lld) = %lld\n", a, b, power(k).c_str(), n, solve(a, b, k, n));
        long long total = 0;
        printf("  level sums ");
        for (size_t i = 0; i < sums.size(); i++) {
            printf(i ? " + %lld" : "%lld", sums[i]);
            total += sums[i];
        }
        printf(" = %lld\n", total);
        printf("  master theorem: %s\n", master(a, b, k).c_str());
    }

    // T(n) = T(n-1) + n is not of the form a*T(n/b) + f(n): unroll it instead.
    long long t = 1;
    for (long long m = 2; m <= n; m++) t += m;
    printf("T(n) = T(n-1) + n: T(%lld) = %lld = n(n+1)/2 = %lld\n", n, t, n * (n + 1) / 2);
    printf("  master theorem does not apply: Theta(n^2) by iteration\n");
    return 0;
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static long ipow(long base, int e) {
        long r = 1;
        while (e-- > 0) r *= base;
        return r;
    }

    // T(n) = a*T(n/b) + n^k, with T(1) = 1, evaluated by direct recursion.
    static long solve(int a, int b, int k, long n) {
        if (n == 1) return 1;
        return a * solve(a, b, k, n / b) + ipow(n, k);
    }

    // Work on each level of the recursion tree: nodes on the level * cost per node.
    static List<Long> levelSums(int a, int b, int k, long n) {
        List<Long> sums = new ArrayList<>();
        long nodes = 1, size = n;
        while (size > 1) {
            sums.add(nodes * ipow(size, k));
            nodes *= a;
            size /= b;
        }
        sums.add(nodes); // the leaves, T(1) = 1 each
        return sums;
    }

    static String power(int e) {
        return e == 1 ? "n" : "n^" + e;
    }

    // Compare a with b^k, i.e. n^(log_b a) with f(n) = n^k.
    static String master(int a, int b, int k) {
        if (a < ipow(b, k)) return "case 3, the root dominates: Theta(" + power(k) + ")";
        if (a == ipow(b, k)) return "case 2, every level equal: Theta(" + power(k) + " log n)";
        int e = 0;
        while (ipow(b, e) < a) e++;
        String crit = ipow(b, e) == a ? power(e) : "n^(log_" + b + " " + a + ")";
        return "case 1, the leaves dominate: Theta(" + crit + ")";
    }

    public static void main(String[] args) {
        long n = 16;
        int[][] params = {{2, 2, 1}, {2, 2, 2}, {4, 2, 1}};
        for (int[] p : params) {
            int a = p[0], b = p[1], k = p[2];
            List<Long> sums = levelSums(a, b, k, n);
            System.out.printf("T(n) = %dT(n/%d) + %s: T(%d) = %d%n", a, b, power(k), n, solve(a, b, k, n));
            long total = sums.stream().mapToLong(Long::longValue).sum();
            List<String> parts = new ArrayList<>();
            for (long s : sums) parts.add(Long.toString(s));
            System.out.printf("  level sums %s = %d%n", String.join(" + ", parts), total);
            System.out.printf("  master theorem: %s%n", master(a, b, k));
        }

        // T(n) = T(n-1) + n is not of the form a*T(n/b) + f(n): unroll it instead.
        long t = 1;
        for (long m = 2; m <= n; m++) t += m;
        System.out.printf("T(n) = T(n-1) + n: T(%d) = %d = n(n+1)/2 = %d%n", n, t, n * (n + 1) / 2);
        System.out.println("  master theorem does not apply: Theta(n^2) by iteration");
    }
}
Watch it run

Step through it

Running on n = 16: 2T(n/2) + n, 2T(n/2) + n², 4T(n/2) + n, T(n − 1) + n; T(1) = 1

T(n) = 2T(n/2) + n, T(1) = 1, n = 1616work on the level16a = 2 subproblems, each of size n/b = n/2cost outside the recursion: f(n) = n
Step 1

Level 0: the root does n = 16 work

This is merge sort's recurrence: split into 2 halves, solve each recursively, and do n work to merge. The root of the recursion tree is the top-level call; its own work, not counting the recursive calls, is f(16) = 16.

Output
1 / 13
4

Substitution Method and Iteration Method

In the substitution method you guess the form of the answer and prove it by mathematical induction. To show T(n) = 2T(n/2) + n is O(n log n), assume T(n/2) ≤ c(n/2) log(n/2) for the smaller input. Then T(n) ≤ 2c(n/2)(log n − 1) + n = cn log n − cn + n, which is at most cn log n whenever c ≥ 1. The inductive step holds, so T(n) = O(n log n).

In the iteration method you expand the recurrence until the pattern is clear. For binary search, T(n) = T(n/2) + 1 = T(n/4) + 2 = T(n/8) + 3 = … = T(n/2ᵏ) + k. The expansion stops when n/2ᵏ = 1, that is k = log₂ n, so T(n) = T(1) + log₂ n = Θ(log n).

  • Substitution needs a good guess; recursion trees supply one
  • The inductive step must prove exactly the same bound, with the same constant: proving T(n) ≤ cn + 1 when you assumed ≤ cn is a failed proof
  • Iteration turns a recurrence into a sum, often a geometric or arithmetic series
5

Recursion Tree Method

  1. Draw – the root costs f(n); it has a children, each of size n/b.
  2. Sum each level – level i has aⁱ nodes, each costing f(n/bⁱ).
  3. Count the levels – log_b n levels until the size reaches 1.
  4. Add – total = sum of the level sums, including n^(log_b a) leaves.

The recursion tree method draws each call as a node labelled with the work it does outside its own recursive calls. Summing each level and then adding the levels gives the total. The tracer builds the tree for T(n) = 2T(n/2) + n at n = 16: five levels of 16 each, for a total of 80.

The shape of the level sums tells you the answer before any algebra. If they are equal, multiply the work per level by the number of levels, log_b n. If they fall geometrically, the root dominates and T(n) = Θ(f(n)). If they rise geometrically, the leaves dominate: there are n^(log_b a) of them, and that is the answer.

  • Drawing two or three levels is enough to see the pattern; the full tree is only for small n
  • A lopsided tree (T(n/3) + T(2n/3)) has branches of different depth; bound it by its longest path
6

The Master Theorem

  1. Identify – read off a, b and f(n).
  2. Compute – work out n^(log_b a), the number of leaves.
  3. Compare – pick the case, and check the regularity condition in case 3.

The master theorem solves any recurrence of the form T(n) = aT(n/b) + f(n) with constants a ≥ 1 and b > 1 by comparing f(n) with n^(log_b a), the number of leaves in the recursion tree. It is the recursion-tree argument done once, in general.

It does not apply to every recurrence. It fails when the problem shrinks by subtraction, as in T(n − 1) + n; when a or b is not a constant; and when f(n) differs from n^(log_b a) by less than a polynomial factor, as in T(n) = 2T(n/2) + n / log n. The extended version handles f(n) = Θ(n^(log_b a) logᵏ n) with k ≥ 0, giving Θ(n^(log_b a) logᵏ⁺¹ n). It is covered as a tool in divide and conquer; here it is the general form of the recursion tree.

The three cases of the master theorem
CaseConditionResultExample
1: leaves dominatef(n) = O(n^(log_b a − ε)) for some ε > 0Θ(n^(log_b a))T(n) = 9T(n/3) + n → Θ(n²)
2: all levels equalf(n) = Θ(n^(log_b a))Θ(n^(log_b a) log n)T(n) = 2T(n/2) + n → Θ(n log n)
3: root dominatesf(n) = Ω(n^(log_b a + ε)) and a·f(n/b) ≤ c·f(n), c < 1Θ(f(n))T(n) = 2T(n/2) + n² → Θ(n²)
  • Binary search: a = 1, b = 2, n^0 = 1 = f(n) → case 2 → Θ(log n)
7

Linear Recurrence Relations

In discrete mathematics a linear homogeneous recurrence with constant coefficients has the form aₙ = c₁aₙ₋₁ + c₂aₙ₋₂ + … + cₖaₙ₋ₖ. It is solved by the characteristic equation: substitute aₙ = rⁿ to get rᵏ = c₁rᵏ⁻¹ + … + cₖ, find its roots, and combine them.

Take aₙ = 5aₙ₋₁ − 6aₙ₋₂ with a₀ = 1 and a₁ = 4. The characteristic equation r² − 5r + 6 = 0 has roots 2 and 3, so aₙ = A·2ⁿ + B·3ⁿ. The initial conditions give A + B = 1 and 2A + 3B = 4, so A = −1 and B = 2: aₙ = 2·3ⁿ − 2ⁿ. Check: a₂ = 5·4 − 6·1 = 14, and 2·9 − 4 = 14. The same method turns the Fibonacci recurrence into Binet's formula, F(n) = (φⁿ − ψⁿ)/√5.

  • Distinct roots r₁, r₂: aₙ = A·r₁ⁿ + B·r₂ⁿ
  • Repeated root r: aₙ = (A + B·n)·rⁿ
  • Homogeneous means no term without some aₙ₋ᵢ; non-homogeneous recurrences add a particular solution to this general one