← Fundamentals
Fundamentals

Boundaries and loop invariants

What does the state promise about everything processed so far?

An invariant gives each piece of loop state a precise meaning throughout a computation.

Outcome

State and preserve a processed-prefix invariant, including empty input, trailing runs and summaries joined repeatedly.

Terminology (3)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Loop invariant
A precise claim maintained at a specified point on every iteration.
Half-open range
A range that includes its start and excludes its end.
Boundary summary
Facts about a segment’s ends retained so that later combinations preserve the segment’s meaning.

State meanings that survive each step

A loop invariant is a claim that holds at a chosen point on every iteration. Establish it before the first step, check that one step preserves it, then combine it with the stopping condition to explain the result. A useful claim describes which input has been accounted for and what the accumulated fields mean.

The same reasoning applies when a scan returns a summary for another operation to combine. Each returned field must keep its promised meaning for the whole segment, including empty segments and unfinished boundary runs. A correct final total alone does not establish that the summary can be reused.

01Account for the processed prefix

Check that the scan accounts for the whole batch

A sensor-batch report needs both the number of readings above a threshold and the longest uninterrupted high run. The export is divided into chunks, and the combined report works with compact chunk summaries. Check that each scan accounts for every reading, then that a returned summary still means what the next join expects.

The report first needs a traversal that accounts for every reading. Use this small sum probe to check where next points and which samples total already contains. Predict the final pair, then state what must hold before each test, including the first.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const samples = [3, 1, 7];
let next = 0;
let total = 0;

while (next < samples.length) {
  total += samples[next];
  next += 1;
}

console.log("next", next, "total", total);
Which pair prints?
Loading The boundary describes the sum…
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --skipLibCheck --target es2022 --module nodenext --types node && node main.ts

Save one complete example at a time under the shown filename in a fresh folder. Run the shown command. The browser lab supplies its editor, input fixtures and runner.

02Name the current run

Separate the current high run from the longest event

The total qualifying count cannot show whether high readings were consecutive. The next probe maintains a current run while scanning the sensor batch. Predict its final value, then compare it with the longest run anywhere.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const samples = [7, 7, 0, 7];
let run = 0;

for (const value of samples) {
  if (value > 5) run += 1;
  else run = 0;
}

console.log("suffix", run);
What prints?

03Preserve reusable boundary facts

Combine summaries without losing a crossing run

The report’s join receives summaries rather than the original readings. Before combining the full records, test the boundary calculation: the left segment ends with two high readings and the right begins with three. Their own best runs are at most three. Predict the crossing run.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const leftSuffix = 2;
const rightPrefix = 3;
const localBest = 3;

console.log("local", localBest, "crossing", leftSuffix + rightPrefix);
Which report prints?

04Practice

Repair the sensor summary

Input is threshold, chunk count, then each chunk’s length and integer readings. A qualifying reading is strictly above threshold. Supplied exports have at most 32 chunks of at most 512 readings each; readings and threshold are between -1000 and 1000. Counts and lengths are nonnegative and match the data. These are supplied input assumptions, not a validation task.

Summary reports length, prefix, suffix and best in that order. Prefix and suffix count qualifying readings at the segment’s ends; best counts the longest qualifying run anywhere. The final report describes the concatenation of all chunks in input order.

Start the lab

Include every sample, account for trailing runs, then preserve summary meaning across repeated joins.

  1. easy · F-INVARIANT-V4-1 Cover the full chunk
  2. medium · F-INVARIANT-V4-2 Summarize the open run
  3. hard · F-INVARIANT-V4-3 Join reusable summaries
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.