Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Correctness: Invariants & Proofs

Loop invariants, induction and termination: knowing an algorithm works before you run it.

Jon Bentley proved a binary search correct in Programming Pearls, and Joshua Bloch wrote the same loop into Java's standard library. In 2006 Bloch reported that both fail on arrays of more than about a billion elements, because (low + high) / 2 overflows. The proof was sound for mathematical integers, and the program ran on 32-bit ones. This lesson is about proofs that hold, and about stating exactly what they assume.

What you’ll learn

  • Write a specification as a precondition and a postcondition, and distinguish partial from total correctness.
  • Prove a loop correct with an invariant (initialization, maintenance, termination), and prove that it stops with a variant.
  • Prove insertion sort, binary search and Euclid's algorithm correct, and prove recursive algorithms correct by induction.
  • Use invariants to write two-pointer, sliding-window and binary-search loops without off-by-one errors, and check them with assertions.

What "correct" means

To prove a program correct you first have to say what correct means. A specification has two parts: a precondition, what the program may assume about its input, and a postcondition, what it promises about its output. For a lower-bound binary search: precondition, the array a[0..n−1]a[0..n-1] is sorted; postcondition, the returned index ii is the first one with a[i]≥xa[i] \ge x, or nn if there is none.

Two levels of guarantee are standard. Partial correctness: if the program stops, its output satisfies the postcondition. Total correctness: in addition, it always stops. So a correctness proof has two parts, and the second, termination, is the one most often forgotten.

Think first Is a program that never stops partially correct for every specification?

Yes. Partial correctness only constrains the outputs of runs that stop, and this program has none, so it satisfies every postcondition vacuously. That is why total correctness adds termination as a separate obligation.

Loop invariants

A loop invariant is a statement about the program's variables that holds every time control reaches the top of the loop. To use one, prove three things:

  1. Initialization: it holds before the first iteration.
  2. Maintenance: if it holds before an iteration, and the loop condition is true, it holds after the iteration.
  3. Termination: when the loop exits, the invariant together with the negated loop condition implies the postcondition.

This is induction on the number of iterations, with a final step that points at the goal.

python
def insertion_sort(a):
    for j in range(1, len(a)):
        # invariant: a[0..j-1] holds the original a[0..j-1], sorted
        key = a[j]
        i = j - 1
        while i >= 0 and a[i] > key:    # shift larger keys one slot right
            a[i + 1] = a[i]
            i -= 1
        a[i + 1] = key
    # exit: j has reached len(a), so all of a is sorted
    return a
DerivationInsertion sort is correct
  1. Initialization (j=1j = 1): the prefix a[0..0]a[0..0] is one item, the original a[0]a[0], and one item is sorted.

  2. a[0]≤⋯≤a[i]  ≤  key  <  a[i+2]≤⋯≤a[j]a[0] \le \dots \le a[i] \;\le\; \texttt{key} \;<\; a[i+2] \le \dots \le a[j]

    Maintenance. The inner loop shifts each key of the prefix that is larger than key one slot right, keeping their order, and stops at the first key ≤\le key or at the left end. Dropping key into the gap at i+1i + 1 leaves a sorted prefix one longer, holding the original a[0..j]a[0..j]:

  3. j=n  ⟹  a[0..n−1] is a sorted permutation of the inputj = n \;\Longrightarrow\; a[0..n-1] \text{ is a sorted permutation of the input}

    Termination. The outer loop exits when j=nj = n, and the invariant then says that a[0..n−1]a[0..n-1] is the original input, sorted: the postcondition. Both loops stop, since jj counts up to nn and ii counts down to −1-1.

Binary search, proved

Binary search is the classic test of writing a loop correctly: Bentley, citing Knuth, notes that the first binary search was published in 1946 but the first one without bugs only in 1962. The cure is to choose the invariant first and derive the code from it. For the lower bound, the first index with a[i]≥xa[i] \ge x, use the half-open range [lo,hi)[lo, hi):

python
def lower_bound(a, x):
    """First index i with a[i] >= x, or len(a). Precondition: a is sorted."""
    lo, hi = 0, len(a)
    while lo < hi:
        # invariant: a[i] < x for all i < lo, and a[i] >= x for all i >= hi
        mid = lo + (hi - lo) // 2      # lo <= mid < hi
        if a[mid] < x:
            lo = mid + 1               # the answer is right of mid
        else:
            hi = mid                   # the answer is mid or left of it
    return lo                          # lo == hi
DerivationProof of lower_bound
  1. a[i]<x for all i<lo,a[i]≥x for all i≥hia[i] < x \text{ for all } i < lo, \qquad a[i] \ge x \text{ for all } i \ge hi

    The invariant, for a sorted array:

  2. Initialization: with lo=0lo = 0 and hi=nhi = n both index sets are empty, so it holds vacuously. Maintenance: lo≤mid<hilo \le mid < hi, so midmid is a real index. If a[mid]<xa[mid] < x, then a[i]≤a[mid]<xa[i] \le a[mid] < x for every i≤midi \le mid, and moving lolo to mid+1mid + 1 keeps the left half true; otherwise a[i]≥a[mid]≥xa[i] \ge a[mid] \ge x for every i≥midi \ge mid, and moving hihi to midmid keeps the right half true.

  3. hi−lo  ⟶  at most ⌊(hi−lo)/2⌋⟹at most ⌊log⁡2n⌋+1 iterationshi - lo \;\longrightarrow\; \text{at most } \lfloor (hi - lo)/2 \rfloor \quad\Longrightarrow\quad \text{at most } \lfloor \log_2 n \rfloor + 1 \text{ iterations}

    Termination. The variant hi−lohi - lo is a natural number that strictly decreases, because mid+1>lomid + 1 > lo and mid<himid < hi; in fact it at least halves. At exit lo=hilo = hi, and the invariant says that lolo is the first index with a[i]≥xa[i] \ge x.

Check your understanding

A variant of lower_bound keeps while lo < hi and mid = lo + (hi - lo) // 2, but sets lo = mid instead of lo = mid + 1 when a[mid]<xa[mid] < x. What goes wrong?

  1. It returns an index one too small
  2. Nothing: lo = mid also keeps the invariant
  3. It can loop forever: when hi=lo+1hi = lo + 1 and a[lo]<xa[lo] < x, mid equals lo and the range never shrinks
  4. It overflows on large arrays
Show the answer

C. It can loop forever: when hi=lo+1hi = lo + 1 and a[lo]<xa[lo] < x, mid equals lo and the range never shrinks

The invariant survives, since every i<midi < mid still has a[i]<xa[i] < x, but the variant does not: with hi=lo+1hi = lo + 1, mid is lolo, and setting lo = mid changes nothing. Partial correctness holds while total correctness fails, which is exactly why termination needs its own argument.

Termination: variants, and Euclid

A variant, or ranking function, proves termination: a quantity that is a natural number whenever the loop is about to iterate, and that strictly decreases in every iteration. Natural numbers cannot decrease forever, so the loop stops. More generally, any well-founded order, one with no infinite descending chain, will do: pairs compared lexicographically prove that nested or interleaved loops stop.

Euclid's algorithm shows both halves of a proof at work:

python
def gcd(a, b):                # precondition: a, b >= 0, not both 0
    while b != 0:
        # invariant: gcd(a, b) is the gcd of the original inputs
        # variant:   b, a natural number
        a, b = b, a % b
    return a                  # b == 0, and gcd(a, 0) = a
DerivationEuclid, totally correct
  1. gcd⁡(a,b)=gcd⁡(b, a mod b)(b>0)\gcd(a, b) = \gcd(b,\ a \bmod b) \qquad (b > 0)

    Invariant. With q=⌊a/b⌋q = \lfloor a/b \rfloor we have a mod b=a−qba \bmod b = a - qb. Any dd that divides aa and bb divides a mod ba \bmod b, and any dd that divides bb and a mod ba \bmod b divides a=qb+(a mod b)a = qb + (a \bmod b). The two pairs have the same common divisors, hence the same greatest one:

  2. 0  ≤  a mod b  <  b0 \;\le\; a \bmod b \;<\; b

    Variant. The new second number is a mod ba \bmod b, a natural number smaller than bb, so bb strictly decreases and the loop stops:

  3. b=0⟹gcd⁡(inputs)=gcd⁡(a,0)=ab = 0 \quad\Longrightarrow\quad \gcd(\text{inputs}) = \gcd(a, 0) = a

    Exit. The loop exits with b=0b = 0, and every number divides 0, so the invariant becomes the postcondition:

Predict before you look

How many times does the loop body run for gcd(89, 55)?

Show the answer

9

The pairs are (89, 55), (55, 34), (34, 21), (21, 13), (13, 8), (8, 5), (5, 3), (3, 2), (2, 1), and then (1, 0): 9 rounds, every quotient equal to 1. Consecutive Fibonacci numbers are the slowest inputs of their size, which is Lamé's theorem in Euclid's Algorithm in Depth.

Recursion and induction

For a recursive algorithm the invariant becomes an induction hypothesis. To prove f correct on every input, prove it on the base cases, then prove it on an input of size nn assuming that every recursive call, which works on a smaller input, returns the right answer. Calls on inputs of size about n/2n/2 need strong induction, which assumes the claim for all smaller sizes at once.

DerivationMerge sort is correct
  1. Claim P(n)P(n): on any list of length nn, mergesort returns a sorted permutation of it. Base cases n≤1n \le 1: the list comes back unchanged, and it is sorted.

  2. 1  ≤  ⌊n/2⌋  ≤  ⌈n/2⌉  <  n(n≥2)1 \;\le\; \lfloor n/2 \rfloor \;\le\; \lceil n/2 \rceil \;<\; n \qquad (n \ge 2)

    Inductive step, n≥2n \ge 2. The halves have lengths below nn, so by the induction hypothesis both recursive calls return sorted permutations of their halves:

  3. The merge lemma. Merging sorted lists LL and RR keeps the invariant "the output holds the kk smallest items of LL and RR in sorted order, and L[i]L[i], R[j]R[j] are the smallest items not yet output". Taking the smaller of L[i]L[i] and R[j]R[j] preserves it, and when both lists are used up the output is all of their items, sorted. So P(n)P(n) holds.

Recognizing it

Invariants are not only for proofs after the fact: they are the fastest way to write tricky loops correctly. Before coding a two-pointer scan, a sliding window or a binary search, write down what must be true at the top of every iteration, then derive the updates that keep it true. The common patterns:

TechniqueInvariant at the top of each iterationWhy the answer follows
binary search for a boundarya[i]<xa[i] < x for i<loi < lo; a[i]≥xa[i] \ge x for i≥hii \ge hiat lo=hilo = hi, the boundary is lolo
two pointers, pair sum in a sorted arrayno pair that uses an index outside [l,r][l, r] sums to the targetonce l≥rl \ge r, no pair is left
sliding window, longest valid windowa[l..r]a[l..r] is valid, and ll is the smallest start that keeps it validthe longest valid window ending at each rr is examined
Kadane's algorithmcur is the largest sum of a subarray ending at ii; best the largest seen so farevery subarray ends somewhere
prefix sumsP[i]=a[0]+⋯+a[i−1]P[i] = a[0] + \dots + a[i-1]the sum of a[l..r]a[l..r] is P[r+1]−P[l]P[r+1] - P[l]
Dijkstra's algorithmevery settled vertex has its true distanceat the end every reachable vertex is settled
The sliding-window invariant needs a monotone condition: every subwindow of a valid window is valid. Each invariant turns into code; "no pair outside [l,r][l, r] works", for instance, tells you exactly when moving ll or rr is safe.
Check your understanding

For pair sum in a sorted array, ll starts at 0 and rr at n−1n - 1. When a[l]+a[r]<ta[l] + a[r] < t you move ll right. Which invariant justifies that move?

  1. a[l..r]a[l..r] is sorted
  2. No pair that uses an index outside [l,r][l, r] sums to tt
  3. a[l]+a[r]a[l] + a[r] increases at every step
  4. Every pair inside [l,r][l, r] has already been checked
Show the answer

B. No pair that uses an index outside [l,r][l, r] sums to tt

If a[l]+a[r]<ta[l] + a[r] < t, then a[l]+a[j]≤a[l]+a[r]<ta[l] + a[j] \le a[l] + a[r] < t for every j≤rj \le r, so no pair that uses ll can work, and discarding ll keeps the invariant. The case a[l]+a[r]>ta[l] + a[r] > t is symmetric. When the pointers meet, the invariant says that no pair sums to tt.

Testing versus proving. Tests find bugs, but as Dijkstra put it they cannot show their absence. Invariants make tests sharper too: an assert of the invariant inside the loop turns a silent wrong answer into a failure at the very iteration that broke it, and comparing a fast solution with a brute force on thousands of small random inputs, stress testing, catches most of what remains.

Common bugs

  • Mixing inclusive [lo,hi][lo, hi] and half-open [lo,hi)[lo, hi) ranges: choose one, and write the invariant in that convention.
  • An update that does not shrink the range, such as lo = mid with a rounded-down mid: an infinite loop.
  • Forgetting the equal case or duplicates: "the first index with a[i]≥xa[i] \ge x" and "some index with a[i]=xa[i] = x" are different specifications.
  • The empty input: the invariant must hold, and the loop must exit, when n=0n = 0.
  • Arithmetic that overflows fixed-width integers, which no reasoning about mathematical integers will catch.

Key takeaways

  • A specification is a precondition and a postcondition; partial correctness says the output is right if the program stops, and total correctness adds that it always stops.
  • A loop invariant must hold initially, be preserved by every iteration, and with the negated loop condition imply the postcondition; a variant, a natural number that strictly decreases, proves termination.
  • Insertion sort keeps a sorted prefix; binary search keeps "a[i]<xa[i] < x left of lolo, a[i]≥xa[i] \ge x from hihi on" with variant hi−lohi - lo; Euclid keeps the gcd with variant bb.
  • Recursive algorithms are proved by strong or structural induction: assume correctness on smaller inputs and prove it for the whole.
  • A proof is about a model: (lo + hi) / 2 is right for mathematical integers and wrong for 32-bit ones. Tests find bugs; invariants explain why there are none.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A sorting function returns [] for every input. Which part of the specification does it violate?

  1. The precondition
  2. "The output is sorted"
  3. "The output is a permutation of the input"
  4. Termination
Show the answer

C. "The output is a permutation of the input"

The empty list is sorted and the function always stops; what fails is the clause that the output holds exactly the input's items. A specification without that clause would be satisfied by this useless function.

Question 2

Which quantity proves that lower_bound, with while lo < hi, terminates?

  1. midmid, which moves toward the answer
  2. hi−lohi - lo, a natural number that strictly decreases in every iteration
  3. x−a[mid]x - a[mid], which shrinks
  4. lolo, which never decreases
Show the answer

B. hi−lohi - lo, a natural number that strictly decreases in every iteration

A variant must be a natural number, or come from a well-founded order, and strictly decrease in every iteration. hi−lohi - lo does, because lo≤mid<hilo \le mid < hi makes both updates shrink it.

Question 3

Why can mid = (lo + hi) / 2 break binary search in Java on huge arrays, but never in Python?

  1. Java's int has 32 bits, so lo+hilo + hi can exceed 231−12^{31} - 1 and wrap to a negative number, while Python's integers are unbounded
  2. Python rounds division differently
  3. Python checks array bounds and Java does not
  4. Java arrays cannot hold more than a billion elements
Show the answer

A. Java's int has 32 bits, so lo+hilo + hi can exceed 231−12^{31} - 1 and wrap to a negative number, while Python's integers are unbounded

The proof assumed mathematical integers. In 32-bit arithmetic, lo+hilo + hi overflows once it passes 231−12^{31} - 1, about 2.1 billion, which can happen on arrays of more than about 2302^{30} elements. lo + (hi - lo) / 2 computes the same value without the large sum.

Question 4

To prove by strong induction that merge sort is correct on lists of every length, what may you assume when proving it for length nn?

  1. That it is correct for length n−1n - 1 only
  2. That merging is correct, which needs no proof
  3. That the input is already sorted
  4. That it is correct on every input shorter than nn
Show the answer

D. That it is correct on every input shorter than nn

The halves have lengths ⌊n/2⌋\lfloor n/2 \rfloor and ⌈n/2⌉\lceil n/2 \rceil, both smaller than nn when n≥2n \ge 2 but not equal to n−1n - 1 in general, so you need the hypothesis for all smaller lengths: strong induction. The merge's correctness is a separate lemma, with its own loop invariant.

Question 5

A proposed invariant holds initially and is preserved by every iteration, but at loop exit it does not imply the postcondition. What should you do?

  1. Nothing: initialization and maintenance are enough
  2. Strengthen the invariant until, together with the exit condition, it implies the postcondition
  3. Weaken the postcondition until it follows
  4. Add more test cases
Show the answer

B. Strengthen the invariant until, together with the exit condition, it implies the postcondition

"xx is an integer" is an invariant of almost any loop, and useless. A good invariant is strong enough to finish the proof and weak enough to stay true; it usually says what the loop has achieved so far, as in "a[0..j−1]a[0..j-1] is sorted".

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 2, "Getting Started".
  • J. Bentley, Programming Pearls, 2nd ed. (Addison-Wesley, 2000), column 4, "Writing Correct Programs".
  • D. Gries, The Science of Programming (Springer, 1981).
  • J. Bloch, "Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken," Google Research Blog (2006).