Reservoir sampling (deterministic RNG contract)
Problem
Using rng = random.Random(seed): - Copy the first k items into the reservoir in order. - For each later item at 0-based index i ≥ k, call j = rng.randint(0, i) (inclusive) exactly once; if j < k, replace reservoir[j]. - Return the reservoir. If the stream has fewer than k items, return all of them.
Signature
def reservoir_sample(stream, k: int, seed: int) -> list: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> reservoir_sample([1, 2], 5, seed=0) == [1, 2]
True
>>> reservoir_sample(range(3), 3, seed=42) == [0, 1, 2]
TrueHints
Copy the first k items; for each later item, draw j = rng.randint(0, i) exactly once.
If j < k, replace reservoir[j]; keep the exact RNG contract (seed and call sequence).
Each item survives with probability k/n — no whole stream stored.
Reference solution
import random
def reservoir_sample(stream, k, seed):
rng = random.Random(seed)
res = []
for i, item in enumerate(stream):
if i < k:
res.append(item)
else:
j = rng.randint(0, i)
if j < k:
res[j] = item
return resWhat a strong solution covers
- Proves each item survives with probability k/n (induction).
- Single pass with O(k) memory.
- Follow-ups: weighted reservoir (A-Res, keys u^(1/w)) and stratified sampling to match a target distribution.
Common mistakes
randint(0, i − 1)orrandint(1, i)off-by-one (biased)- storing the whole stream.