Data Structures & Algorithms / Module 10: Correctness and reviewing AI code

Topic 10.1

Loop invariants

One sentence that stays true on every pass, and how to use it to show a loop is right.

9 min · intermediate

Watch: at every step, the promise "this is the biggest so far" is checked. If it breaks even once, the final answer must be wrong.

0123best-3-7-1-5-3
  • moving now
  • passed / marked
  • finished / the result
Step 1 of 5

Start with best = the first element (-3). The promise that must hold on every pass: best is the largest of everything seen so far.

An invariant is a statement that is true before the loop, stays true after every pass, and at the end gives you the answer.

Three questions

  1. Start: is the sentence true before the first pass?
  2. Every pass: if it's true at the start of a pass, is it still true at the end?
  3. End: when the loop stops, do the sentence and the stopping condition together give the answer you want?

It's like climbing a ladder: if you can get onto the first rung, and from any rung you can reach the next, then you can reach the top.

Example: finding the largest

Invariant: best is the largest of a[0] to a[i − 1]. Choose "best = 0" in the figure. The list is all negative, so even before the first pass the sentence is false: 0 isn't in the list. The loop still runs without errors and returns 0. The first question ("is it true at the start?") finds this bug right away, without having to guess an input that breaks it.

Code, for programmersThe invariant written as a comment
function max(a) {
  if (a.length === 0) throw new Error("empty list");
  let best = a[0];
  // invariant: best is the largest of a[0..i-1]
  for (let i = 1; i < a.length; i++) {
    if (a[i] > best) best = a[i];
    // still true: best is the largest of a[0..i]
  }
  // loop ended with i = a.length, so best is the largest of the whole list
  return best;
}

Invariants in algorithms you've seen

  • Binary search: if the target exists, it's always between lo and hi.
  • Insertion sort: the part a[0..i − 1] is always sorted.
  • Two pointers: the right pair is never outside lo and hi.
  • Dijkstra: every settled place has its true shortest distance.

Quiz

  1. A loop invariant must be true…

  2. max() starts with best = 0. Which input breaks it?

  3. Insertion sort's invariant?

0 of 3 answered.