cs-024 — The Off-By-One Museum
| Field | Value |
|---|---|
| id | cs-024 |
| difficulty | Advanced |
| topics | off-by-one, testing |
| lecture | lecture-06 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | the full Block I-III toolbox and proof-shaped reasoning |
| objective | make and justify design decisions where the method itself is the challenge |
| solution | held by the instructor; discussed after the attempt |
Problem
Three near-identical loops that each misbehave by one step. Diagnose each, fix minimally, and state the lesson each artefact teaches.
Your deliverable is the computed aggregates for the worked instance, the accumulator update rules, and one test input that breaks a careless initialisation. If the problem is ambiguous anywhere, state the assumption you are making and carry on — a stated assumption is part of a good answer.
Examples
- Input: three loops: (a) range(1, n) summing 1..n, (b) while i <= n: i += 2 summing 1..n, (c) i = n; while i > 0: i -= i // 4 + 1
- Output: the diagnosis: (a) misses the last value n; (b) visits only odd i, so every even value is skipped; (c) terminates, with a step count that grows logarithmically
Solve for the worked instance first. Then ask what would change if one number, name, or condition were replaced by something stranger.
What to notice
- For each loop, ask: does the last needed value get processed? What strictly changes each iteration?
- Every aggregate here is a small machine: state + update rule.
- The initial value is part of the algorithm, not a detail.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Where exactly would this solution break first if the input grew to a million items — and would anything break at all?"
Constraints and assumptions
- Difficulty: Advanced (functions, dictionaries, and algorithmic reasoning assumed).
- Topics: off-by-one, testing.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for the attack plan; the full argument may exceed the box - outline the proof strategy instead of grinding details.
- Optional stretch (not required): describe an alternative approach and say when it beats the obvious one.
Hints and extension
- First nudge: identify the pattern the worked instance uses before computing anything.
- If stuck after three minutes, write the input/output line you expect and trace the smallest example by hand.
- After the reveal, attempt the extension below before the next lecture.
- Extension challenge: Construct an input that maximises the trace length and count the steps exactly.