Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Think like a problem solver
EXPERIMENT 03 / 66

Know why it works.

Connect initialisation, maintenance, and termination to an actual loop.

BY NAVAN SAMI◷ 7 MIN READSTARTERCONCEPT

01 Model the idea

A loop invariant is a statement that remains true at a defined point in every iteration. To use it as a correctness argument, show it holds initially, survives each update, and implies the required result when the loop ends. Also show termination: an invariant alone does not prove the loop will finish. This discipline exposes off-by-one errors and ambiguous state before performance analysis begins.

THE THING THAT MUST STAY TRUE

The aggregate describes exactly the processed prefix.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
START the aggregate at its identity
EXTEND the processed prefix one item at a time
USE the invariant when the prefix reaches the input end

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

proof_and_invariants.py
values = [3, 5, 2]
total = 0
for count, value in enumerate(values, start=1):
    total += value
    print(count, total)
assert total == sum(values)
↳ EXPECTED OUTPUT
1 3
2 8
3 10
  1. 1

    Initially total is the sum of zero processed values. After adding the next value, it becomes the sum of one longer prefix.

  2. 2

    The invariant is defined after each update: total equals the sum of the first count elements. At termination, that prefix is the whole input.

  3. 3

    The finite iterable supplies termination. For a while loop you would additionally identify a measure that moves toward a stopping condition.

04 Count the cost

TIME

O(n)

SPACE

O(1) auxiliary

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Express and test the invariant for a running maximum on nonempty input.

Reveal one possible solution +
one_possible_solution.py
values = [3, 5, 2]
best = values[0]
for index in range(len(values)):
    best = max(best, values[index])
    assert best == max(values[:index + 1])
print(best)

06 Check your reasoning

QUICK SIGNAL CHECK

What else is needed besides a maintained invariant?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.