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 be the claim "the procedure is correct on every input of size ": it halts and returns an acceptable output. A proof by strong induction on has three ingredients.
- 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.
- Base cases. Show directly for the sizes where the procedure does not recurse.
- Inductive step. Assume for every (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 .
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 for an integer , square the result of computing , and multiply by one extra when is odd.
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 * xClaim. For every integer , POWER(x, n) returns .
- Size measure. itself. For , , so the argument strictly decreases.
- Base case : line 2 returns .
- Inductive step. Let and assume the claim for all smaller exponents. Line 3 calls
POWERwith , so . If is even, and . If is odd, and .
The same induction also bounds the cost. Each call does at most 2 multiplications and halves , so there are non-trivial calls for and at most multiplications, instead of the of the naive loop.
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++, does not fit in a 64-bit integer, so this version computes every power modulo the prime and checks it against a slow loop. The multiplication counts are the same:
#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 the counts include multiplications by the starting value 1, which a tuned version would skip; for large the logarithmic count wins by a wide margin.
Example 2: recursive binary search
The procedure searches a sorted array for , but only inside the range .
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 is sorted, the call returns an index in with when occurs in , and otherwise.
- Size measure. , the length of the range.
- Base case : the range is empty, does not occur in it, and line 2 returns .
- Inductive step. Let , so . If , line 5 is correct. If , then because is sorted every element of is less than , so occurs in exactly when it occurs in . That range has length , so by the hypothesis line 7 returns a correct answer for it, which is a correct answer for . The case is symmetric, with the range of length .
Both recursive ranges are strictly shorter because 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 in the range "to be safe". Try to redo the inductive step: the new range has length , and when we have , so the length is still . The measure does not decrease, the induction hypothesis does not apply, and the proof fails. The proof failing at exactly points to the bad instance: a one-element range whose element is less than .
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":
#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 nodes, the call returns whether the tree is balanced and its height". The induction on then goes through directly.
# 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 , 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 ?
- That the procedure is correct for size
- That every recursive call on an input of size less than returns a correct answer
- That the procedure never recurses
- That the input is sorted
Why does the buggy binary search with BIN-SEARCH(a, x, mid, hi) fail the proof?
- Because can be negative
- Because when the new range has the same length, so the size measure does not decrease
- Because the array is not sorted
- Because it returns too early
For , how many non-trivial calls (calls with ) does POWER(x, n) make?
Why does the balanced-tree check return the height as well as a yes/no answer?
- To make the code shorter
- Because the parent's answer depends on the subtrees' heights, so the induction hypothesis must provide them
- Because Python functions must return tuples
- Because the height is the output the user asked for