Uniform Sampling From a One-Pass Stream
Statistics & ExperimentsModel answerLast updated
Design an O(k)-memory single-pass sampler for a stream of unknown length and prove every element is kept with probability k/n.
You are handed a data stream of items whose length n is not known in advance. You may look at each item exactly once, in order, and you may hold at most O(k) items in memory at any time — you cannot store the stream or revisit it. When the stream ends, you must output exactly k items, and the output must be a uniformly random selection: every item should appear in the result with probability k/n, and ideally every size-k subset of the stream should be equally likely. If the stream turns out to have fewer than k items, return all of them.
Describe the algorithm in enough detail to implement it, then give a rigorous proof of its uniformity (including the off-by-one details of the random draw). Finish with the time and space complexity, the main edge cases and bugs, and at least one natural extension an interviewer might push you toward.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The algorithm (reservoir sampling, Algorithm R)
Maintain a buffer (the reservoir) of up to k items; don't assume you know n.
- Phase 1 (first
kitems): write every arriving item straight into the next free slot. - Phase 2 (item number
t, fort ≥ k+1, 1-indexed): drawjuniformly from{0, 1, …, t−1}. Ifj < k, overwrite reservoir slotjwith the new item; otherwise discard the new item.
One draw does both jobs: P(j < k) = k/t is the probability of admitting the new item, and conditioned on j < k, j is uniform over the k slots, so the victim is chosen uniformly. The intuition for k/t is that after t items a uniform sample must include the newest one with probability exactly k/t, so the algorithm is forced to admit it at that rate.
In code (0-based index i, so the item is number i+1):
def sample(stream, k, rng):
if k < 0: raise ValueError
if k == 0: return []
res = []
for i, x in enumerate(stream):
if i < k:
res.append(x)
else:
j = rng.randrange(i + 1) # uniform in [0, i], i.e. [0, t-1]
if j < k:
res[j] = x
return res
If the stream is shorter than k, the fill phase never ends and all items are returned automatically.
Proof 1: each item survives with probability k/n
Claim. After t ≥ k items have been processed, every one of those t items is in the reservoir with probability k/t. Induct on t.
- Base
t = k: allkitems are present, probability1 = k/k. - Step: assume the claim holds after
t−1items and itemtarrives.- Item
tis admitted with probabilityk/t— exactly what the claim demands. - For an earlier item
x, the hypothesis givesP(x in reservoir) = k/(t−1)before this step. It is lost only iftis admitted and lands onx's slot:(k/t)·(1/k) = 1/t. SoP(x survives) = k/(t−1) · (1 − 1/t) = k/(t−1) · (t−1)/t = k/t. ∎
- Item
Telescoping alternative. An item i > k is admitted with probability k/i and must then avoid eviction at every later step s = i+1, …, n, each of which it survives with probability (s−1)/s. The product collapses:
(k/i)·(i/(i+1))·((i+1)/(i+2))···((n−1)/n) = k/n.
For i ≤ k the same product starts with admission probability 1 and again gives k/n. Working the k = 1 case first (keep item i with probability 1/i, telescope to 1/n) is a good sanity warm-up.
Proof 2 (stronger): every k-subset is equally likely, probability 1/C(t,k)
Matching marginals alone do not guarantee a uniform subset distribution — raising this unprompted is a strong signal. Induct again. Fix a subset S of the first t items.
t ∉ S: the reservoir at timet−1must have been exactlyS(probability1/C(t−1,k)) andtmust be rejected (probability(t−k)/t). Product:(t−k)/(t·C(t−1,k)) = 1/C(t,k).t ∈ S: writeS' = S \ {t}, of sizek−1. The previous reservoir had to beS' ∪ {y}for somey ∉ S'— there aret−1−(k−1) = t−ksuchy— and thentis admitted and evicts preciselyy, with probability(k/t)(1/k) = 1/t. Total:(t−k)·(1/C(t−1,k))·(1/t) = 1/C(t,k).
Both cases agree, so the output is a uniform random k-subset.
Complexity
- Time:
O(n)— one constant-time step and one random draw per item. - Space:
O(k)— optimal, since the answer itself haskitems. - Single pass, with no prior knowledge of
n.
Edge cases and common bugs
k = 0→ return[]early;k < 0→ reject as invalid; empty stream →[].- Off-by-one, the classic bug: with 0-based
i, you needrandrange(i+1)(uniform on[0, i]). Usingrandrange(i)under-admits and skews the result toward late items; usingrandint(0, i+1)skews toward early items. - Duplicates in the stream are fine — sampling is over positions, not distinct values.
- Inject the RNG so tests are deterministic; then run many trials on a small stream and check each item's frequency is near
k/n.
Extensions worth mentioning
- Algorithm L: when
n ≫ k, generating a random number per item dominates the cost. Compute the number of items to skip before the next replacement from a geometric-style distribution, cutting random draws to an expectedO(k(1 + log(n/k)))(the stream is still read fully). - Weighted sampling (A-Res): give item
ithe keyu_i^(1/w_i)withu_iuniform, and keep theklargest keys — each item is then kept with probability proportional to its weight. - Distributed setting: each shard assigns a random key to its items and keeps its local top
k; merge the shards and take the global topk. Fork = 1this is just "keep the item with the smallest hash" — a nice bridge to consistent sampling.