806. Sample k items from a stream with reservoir sampling
Why it matters Sampling production prompts for evaluation and logging pipelines both need fixed-size uniform samples of unbounded streams.
You want a uniform random sample of k log lines or prompts from a stream too big to store. Reservoir sampling keeps exactly k items and gives every item the same chance k / n of ending up in the sample.
Write reservoir(stream, k, seed). Use rng = random.Random(seed). Keep the first k items. For the item at 0-based index i >= k, draw j = rng.randint(0, i) (inclusive) and if j < k replace slot j with it. Return the reservoir list. If the stream has fewer than k items, return them all.
def reservoir(stream, k, seed)Example 1
Input: reservoir(['a', 'b'], 5, 0)
Output: ['a', 'b']
Example 2
Input: stream = range(100), k = 5, seed = 42
Output: [35, 17, 52, 10, 99]
Example 3
Input: stream = iter(range(1000)), k = 3, seed = 7
Output: [929, 989, 360]
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Fill the reservoir with the first k items.
Hint 2
For later items draw j from 0 to i inclusive; replace slot j only when j < k.
Common mistakes
- Drawing from 0 to i - 1 or 0 to n, which biases toward early or late items.
- Calling
len(stream), which fails on a real iterator.
Understand the idea
When item i arrives (0-based), it should be in the sample with probability k / (i + 1). Drawing j uniformly from 0..i and keeping the item when j < k does exactly that, and the slot it replaces is random. By induction every item seen so far stays in with probability k / (i + 1).
a stream shorter than k is returned whole.
j = randint(0, i); if j < k: res[j] = item