Reservoir sampling from a stream
Asked at Jane Street, Jump Trading
A stream emits items one at a time and you do not know its length n in advance (it may not fit in memory). Draw k items so that every item has an equal k/n chance of ending up in your sample.
Implement it in a single pass using memory, then prove each item is kept with probability exactly .
reservoir_sample(range(1000), k=5) -> 5 items, each equally likely
Show a hint
Keep the first k items outright. For the i-th item (i >= k, 0-indexed), decide with the right probability whether it replaces a random one of the k you're holding. What probability makes everything uniform?
Your answer
This one is open-ended. Work it through, then check your reasoning against the full solution.