cs-076 — The Slow-Fast Cycle
| Field | Value |
|---|---|
| id | cs-076 |
| difficulty | Advanced |
| topics | two pointers, termination, cycles |
| lecture | lecture-19 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | functions, dictionaries, and earlier algorithmic patterns |
| objective | design the algorithm, verify it on edges, and argue correctness or trade-offs |
| solution | held by the instructor; discussed after the attempt |
Problem
Detect a cycle in a sequence given only a 'next' function (Floyd's idea). The invariant is about distance; the aha is why they must meet. Proof-shaped thinking.
Your deliverable is the result for the worked instance, the invariant in one sentence, and the termination argument. 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: next(i) cycles: 1->2->3->4->2 (cycle of length 3); slow/fast pointers from 1
- Output: they meet inside the cycle; meeting guaranteed because the gap closes by 1 each step
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
- The gap between fast (2 steps) and slow (1 step) shrinks by exactly 1 per round - so it must reach 0.
- The invariant is the algorithm; the pointers are just bookkeeping.
- If you cannot say what strictly shrinks, the loop can spin forever.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Restate the invariant in your own words — is yours strong enough to prove the answer?"
Constraints and assumptions
- Difficulty: Advanced (functions, dictionaries, and algorithmic reasoning assumed).
- Topics: two pointers, termination, cycles.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for a defensible plan; a complete solution may take longer and that is expected - state where you would resume.
- 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: State the invariant in one sentence and point at the step that preserves it.