← chapter

Reservoir sampling

A uniform random sample of a stream of UNKNOWN length. One pass, O(k) memory, seen once.

The rule

Watch the reservoir

k=3 over A…J. Accept prob k/i shrinks: 3/4, 3/5, 3/6, … Accepted (green) replaces a random slot; rejected (red) → unchanged.

Uniform where others are biased

Reservoir: flat at k/n (spread 0.011). Keep-first-k: step (spread 1.0). Constant-½: skews late (0.43).

Why k/i is exact, not a heuristic

Takeaway — and the book

The right idea makes the impossible routine: a probability instead of a guarantee. Fair sampling of the unstorable, in five lines. 56 chapters: the right structure separates tractable from intractable. Done.