Know why it works.
Connect initialisation, maintenance, and termination to an actual loop.
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 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.
START the aggregate at its identity
EXTEND the processed prefix one item at a time
USE the invariant when the prefix reaches the input end03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
values = [3, 5, 2]
total = 0
for count, value in enumerate(values, start=1):
total += value
print(count, total)
assert total == sum(values)1 3 2 8 3 10
- 1
Initially total is the sum of zero processed values. After adding the next value, it becomes the sum of one longer prefix.
- 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
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
O(n)
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
Express and test the invariant for a running maximum on nonempty input.
Reveal one possible solution +
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
What else is needed besides a maintained invariant?
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.