Intermediate 8 min

Algorithm invariants

An invariant is a condition that remains true at a known point in each step of an algorithm.

How it works

Check the rule at three times. At the beginning, the running sum of zero is correct for an empty prefix. After each iteration, adding the current value extends the prefix by exactly one item. When the loop ends, that prefix is the full list, so the invariant explains the final answer.

Walk through an example

In a running sum, the total before processing index i equals the sum of every item before i. Adding the next item restores the same rule for the next index.

What to watch for

State the rule clearly enough that you can check initialization and each update. A statement that sounds plausible but cannot be checked does not help prove correctness.

Code example

total = 0
for value in [2, 3, 7]:
    total += value
print(total)

Check your understanding

What should total be before processing the third item?

See the example and explanation
Worked example
Given Total starts at zero. The first two items are 2 and 3.
Answer 5

The invariant says total contains exactly what has already been processed, so it must be 2 + 3.

Open practice problem
Next lessonAdjacency lists and matrices