FREE Algorithms LESSON · Algorithms
Correctness before cleverness
Invariants, boundaries, and adversarial examples
A loop invariant is a compressed proof.
Correctness is not confidence accumulated from passing examples. It is an argument that every allowed execution preserves a property strong enough to imply the result. For an iterative algorithm, establish the property before the loop, show each iteration preserves it, and show termination turns it into the postcondition. The art is choosing an invariant that is neither too weak to help nor so strong it cannot be maintained.
Tests find counterexamples; an invariant explains why no counterexample exists inside the model.
The happy path is a weak adversary.
Boundary values, duplicates, empty inputs, overflow, and ties attack the assumptions hidden by typical examples. Property-based tests and deliberately minimal counterexamples are powerful because they search the space around the invariant. When a test fails, reduce it until the false assumption becomes visible rather than patching the symptom.
A one-element counterexample can be more educational than a thousand passing cases.