TExcelTAD
Home › Foundations of Algorithm Analysis › Proving Recursive Algorithms Correct by Induction

Proving Recursive Algorithms Correct by Induction

A loop invariant proves an iterative algorithm correct. For a recursive algorithm the natural tool is induction on the size of the input: assume the recursive calls, which work on smaller inputs, return correct answers, and show that the current call then returns a correct answer too. This lesson turns that idea into a routine you can apply to any recursive procedure, uses it on two classic algorithms, and shows how the same proof finds a non-terminating bug.

If you need a refresher on the principle itself, see Induction and Strong Induction.

The recipe

Let P(m)P(m) be the claim "the procedure is correct on every input of size mm": it halts and returns an acceptable output. A proof by strong induction on mm has three ingredients.

  1. A size measure that is a non-negative integer and strictly decreases in every recursive call. This is what guarantees that the recursion stops, and it is the quantity you induct on.
  2. Base cases. Show P(m)P(m) directly for the sizes where the procedure does not recurse.
  3. Inductive step. Assume P(k)P(k) for every k<mk < m (the strong induction hypothesis). Every recursive call is on a smaller input, so by the hypothesis it returns a correct answer. Show that the procedure combines these answers into a correct answer for size mm.

The inductive step is where you use the specification of the recursive call, not its code. You never "unroll" the recursion in your head; you trust the smaller calls exactly as far as the hypothesis allows.

Example 1: fast exponentiation

To compute xnx^n for an integer n≥0n \ge 0, square the result of computing x⌊n/2⌋x^{\lfloor n/2 \rfloor}, and multiply by one extra xx when nn is odd.

text
POWER(x, n)
1  if n == 0
2      return 1
3  h = POWER(x, floor(n / 2))
4  if n is even
5      return h * h
6  else
7      return h * h * x

Claim. For every integer n≥0n \ge 0, POWER(x, n) returns xnx^n.

  • Size measure. nn itself. For n≥1n \ge 1, ⌊n/2⌋<n\lfloor n/2 \rfloor < n, so the argument strictly decreases.
  • Base case n=0n = 0: line 2 returns 1=x01 = x^0.
  • Inductive step. Let n≥1n \ge 1 and assume the claim for all smaller exponents. Line 3 calls POWER with ⌊n/2⌋<n\lfloor n/2 \rfloor < n, so h=x⌊n/2⌋h = x^{\lfloor n/2 \rfloor}. If nn is even, n=2⌊n/2⌋n = 2\lfloor n/2 \rfloor and h⋅h=xnh \cdot h = x^n. If nn is odd, n=2⌊n/2⌋+1n = 2\lfloor n/2 \rfloor + 1 and h⋅h⋅x=xnh \cdot h \cdot x = x^n.

The same induction also bounds the cost. Each call does at most 2 multiplications and halves nn, so there are ⌊lg⁡n⌋+1\lfloor \lg n \rfloor + 1 non-trivial calls for n≥1n \ge 1 and at most 2(⌊lg⁡n⌋+1)2(\lfloor \lg n \rfloor + 1) multiplications, instead of the n−1n - 1 of the naive loop.

python · try it yourself
def power(x, n, counter):
    if n == 0:
        return 1
    h = power(x, n // 2, counter)
    if n % 2 == 0:
        counter[0] += 1
        return h * h
    counter[0] += 2
    return h * h * x

for n in [0, 1, 2, 7, 10, 100, 1000]:
    c = [0]
    result = power(3, n, c)
    assert result == 3 ** n
    print(f"n = {n:>4}: correct, {c[0]:>2} multiplications (naive loop: {max(n - 1, 0)})")
n =    0: correct,  0 multiplications (naive loop: 0)
n =    1: correct,  2 multiplications (naive loop: 0)
n =    2: correct,  3 multiplications (naive loop: 1)
n =    7: correct,  6 multiplications (naive loop: 6)
n =   10: correct,  6 multiplications (naive loop: 9)
n =  100: correct, 10 multiplications (naive loop: 99)
n = 1000: correct, 16 multiplications (naive loop: 999)

In C++

In C++, 310003^{1000} does not fit in a 64-bit integer, so this version computes every power modulo the prime 109+710^9 + 7 and checks it against a slow loop. The multiplication counts are the same:

cpp · try it yourself
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <initializer_list>

// 3^1000 does not fit in 64 bits, so this version computes x^n modulo a prime
const std::uint64_t P = 1'000'000'007;

std::uint64_t power(std::uint64_t x, int n, int& counter) {
    if (n == 0) return 1;
    std::uint64_t h = power(x, n / 2, counter);
    if (n % 2 == 0) {
        counter += 1;
        return h * h % P;
    }
    counter += 2;
    return h * h % P * x % P;
}

std::uint64_t naive_power(std::uint64_t x, int n) {   // the slow way: one factor at a time
    std::uint64_t r = 1;
    for (int i = 0; i < n; i++) r = r * x % P;
    return r;
}

int main() {
    for (int n : {0, 1, 2, 7, 10, 100, 1000}) {
        int c = 0;
        std::uint64_t result = power(3, n, c);
        assert(result == naive_power(3, n));
        std::printf("n = %4d: correct, %2d multiplications (naive loop: %d)\n",
                    n, c, std::max(n - 1, 0));
    }
}
n =    0: correct,  0 multiplications (naive loop: 0)
n =    1: correct,  2 multiplications (naive loop: 0)
n =    2: correct,  3 multiplications (naive loop: 1)
n =    7: correct,  6 multiplications (naive loop: 6)
n =   10: correct,  6 multiplications (naive loop: 9)
n =  100: correct, 10 multiplications (naive loop: 99)
n = 1000: correct, 16 multiplications (naive loop: 999)

For tiny nn the counts include multiplications by the starting value 1, which a tuned version would skip; for large nn the logarithmic count wins by a wide margin.

Example 2: recursive binary search

The procedure searches a sorted array aa for xx, but only inside the range a[lo:hi]a[lo:hi].

text
BIN-SEARCH(a, x, lo, hi)          // a is sorted; search a[lo:hi]
1  if lo >= hi
2      return -1                  // empty range
3  mid = floor((lo + hi) / 2)
4  if a[mid] == x
5      return mid
6  if a[mid] < x
7      return BIN-SEARCH(a, x, mid + 1, hi)
8  return BIN-SEARCH(a, x, lo, mid)

Claim. If aa is sorted, the call returns an index ii in [lo,hi)[lo, hi) with a[i]=xa[i] = x when xx occurs in a[lo:hi]a[lo:hi], and −1-1 otherwise.

  • Size measure. m=hi−lom = hi - lo, the length of the range.
  • Base case m≤0m \le 0: the range is empty, xx does not occur in it, and line 2 returns −1-1.
  • Inductive step. Let m≥1m \ge 1, so lo≤mid<hilo \le mid < hi. If a[mid]=xa[mid] = x, line 5 is correct. If a[mid]<xa[mid] < x, then because aa is sorted every element of a[lo:mid+1]a[lo:mid+1] is less than xx, so xx occurs in a[lo:hi]a[lo:hi] exactly when it occurs in a[mid+1:hi]a[mid+1:hi]. That range has length hi−mid−1<mhi - mid - 1 < m, so by the hypothesis line 7 returns a correct answer for it, which is a correct answer for a[lo:hi]a[lo:hi]. The case a[mid]>xa[mid] > x is symmetric, with the range a[lo:mid]a[lo:mid] of length mid−lo<mmid - lo < m.

Both recursive ranges are strictly shorter because midmid itself is excluded from them. That small detail is exactly what the size measure checks, as the next section shows.

Induction finds a bug

A common variant writes BIN-SEARCH(a, x, mid, hi) on line 7, keeping midmid in the range "to be safe". Try to redo the inductive step: the new range has length hi−midhi - mid, and when m=1m = 1 we have mid=lomid = lo, so the length is still 11. The measure does not decrease, the induction hypothesis does not apply, and the proof fails. The proof failing at exactly m=1m = 1 points to the bad instance: a one-element range whose element is less than xx.

python · try it yourself
def search(a, x, lo, hi, keep_mid, depth=0):
    if depth > 50:
        return "no progress after 50 calls"
    if lo >= hi:
        return -1
    mid = (lo + hi) // 2
    if a[mid] == x:
        return mid
    if a[mid] < x:
        return search(a, x, mid if keep_mid else mid + 1, hi, keep_mid, depth + 1)
    return search(a, x, lo, mid, keep_mid, depth + 1)

a = [2, 3, 5, 7, 11, 13]
for x in [11, 4, 14]:
    print(f"x = {x:>2}: correct version -> {search(a, x, 0, len(a), False)},"
          f" buggy version -> {search(a, x, 0, len(a), True)}")
x = 11: correct version -> 4, buggy version -> 4
x =  4: correct version -> -1, buggy version -> no progress after 50 calls
x = 14: correct version -> -1, buggy version -> no progress after 50 calls

In C++

The same experiment in C++, where the special return value -2 stands for "no progress":

cpp · try it yourself
#include <cstdio>
#include <string>
#include <vector>
using namespace std;

const int NO_PROGRESS = -2;   // stands for "no progress after 50 calls"

int search(const vector<int>& a, int x, int lo, int hi, bool keep_mid, int depth = 0) {
    if (depth > 50) return NO_PROGRESS;
    if (lo >= hi) return -1;
    int mid = (lo + hi) / 2;
    if (a[mid] == x) return mid;
    if (a[mid] < x) return search(a, x, keep_mid ? mid : mid + 1, hi, keep_mid, depth + 1);
    return search(a, x, lo, mid, keep_mid, depth + 1);
}

string show(int r) {
    return r == NO_PROGRESS ? "no progress after 50 calls" : to_string(r);
}

int main() {
    vector<int> a = {2, 3, 5, 7, 11, 13};
    int n = (int)a.size();
    for (int x : {11, 4, 14}) {
        printf("x = %2d: correct version -> %s, buggy version -> %s\n", x,
               show(search(a, x, 0, n, false)).c_str(),
               show(search(a, x, 0, n, true)).c_str());
    }
}
x = 11: correct version -> 4, buggy version -> 4
x =  4: correct version -> -1, buggy version -> no progress after 50 calls
x = 14: correct version -> -1, buggy version -> no progress after 50 calls

The buggy version still finds every value that is present; it loops forever only on some absent values. Tests that only search for present values would never notice. The failed proof found the problem without any test.

Strengthening the hypothesis

Sometimes the claim you want is too weak to prove by itself, because the recursive calls must return more information than the caller finally needs. Then you prove a stronger statement. Example: decide whether a binary tree is height-balanced (at every node the two subtrees' heights differ by at most 1). Knowing only that the subtrees are balanced is not enough to decide the parent; you also need their heights. So the procedure returns both, and the claim to prove is: "for every tree with mm nodes, the call returns whether the tree is balanced and its height". The induction on mm then goes through directly.

python · try it yourself
# a tree is None or a tuple (left, right)
def check(t):
    """Return (balanced, height); the empty tree has height -1."""
    if t is None:
        return True, -1
    lb, lh = check(t[0])
    rb, rh = check(t[1])
    return lb and rb and abs(lh - rh) <= 1, 1 + max(lh, rh)

leaf = (None, None)
trees = {
    "single node": leaf,
    "path of 3": ((leaf, None), None),
    "full, 7 nodes": ((leaf, leaf), (leaf, leaf)),
    "lopsided": (((leaf, leaf), (leaf, leaf)), leaf),
}
for name, t in trees.items():
    print(f"{name:<14} balanced={check(t)[0]!s:<5} height={check(t)[1]}")
single node    balanced=True  height=0
path of 3      balanced=False height=2
full, 7 nodes  balanced=True  height=2
lopsided       balanced=False height=3

This pattern, "return more than you were asked for, so the induction works", appears again in dynamic programming and in the augmented search trees of the Data Structures course.

Loops and recursion are the same proof

A loop invariant is induction on the number of iterations: initialization is the base case and maintenance is the inductive step. A recursive proof is induction on the input size, and the decreasing size measure plays the role of the loop variant. Merge sort combines both: its recursive structure is proved correct by induction on nn, and the inductive step relies on MERGE, whose loop invariant you saw in Loop Invariants. The Merge Sort lesson puts the two together.

Test yourself

In a proof by strong induction that a recursive procedure is correct, what may you assume in the inductive step for size mm?

  1. That the procedure is correct for size mm
  2. That every recursive call on an input of size less than mm returns a correct answer
  3. That the procedure never recurses
  4. That the input is sorted

Why does the buggy binary search with BIN-SEARCH(a, x, mid, hi) fail the proof?

  1. Because midmid can be negative
  2. Because when hi−lo=1hi - lo = 1 the new range has the same length, so the size measure does not decrease
  3. Because the array is not sorted
  4. Because it returns −1-1 too early

For n≥1n \ge 1, how many non-trivial calls (calls with n≥1n \ge 1) does POWER(x, n) make?

  1. nn
  2. ⌊lg⁡n⌋+1\lfloor \lg n \rfloor + 1
  3. ⌈n/2⌉\lceil n / 2 \rceil
  4. 2n2^n

Why does the balanced-tree check return the height as well as a yes/no answer?

  1. To make the code shorter
  2. Because the parent's answer depends on the subtrees' heights, so the induction hypothesis must provide them
  3. Because Python functions must return tuples
  4. Because the height is the output the user asked for