KatInterview

Uniform Sampling From a One-Pass Stream

Statistics & ExperimentsModel answer
MediumModel answerStatistics & Experimentsreservoir-samplingrandomized-algorithmsstreaming

Last 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.