Reservoir Sampling from a Stream
Prove uniform sampling without replacement when the input length is unknown and the sample must fit in fixed memory.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 2
- Reading time
- 1 min
In this article2 chapters
Let an arriving item compete with the reservoir
Store the first \(k\) items in a reservoir. When item \(t>k\) arrives, include it with probability \(k/t\), and on inclusion replace a uniform reservoir slot. An older stored item survives that step with probability \(1-1/t\). Its marginal presence becomes \((k/(t-1))(1-1/t)=k/t\).
Uniform marginals alone would be too weak
For a particular \(k\)-subset containing item \(t\), there are \(t-k\) old reservoirs that can produce it by replacement. Each old subset has probability \(1/\binom{t-1}{k}\) by induction, and replacement of the one excluded slot has probability \(1/t\). Multiplying gives \(1/\binom{t}{k}\). A particular subset excluding \(t\) occurs when it was already stored and no replacement happened, giving the same result. For known length, uniform shuffling and taking a prefix works too. Stream processing adds ordering and merging questions when several inputs arrive separately.[1][2]