This is reservoir sampling and I'd seen it before, which saved me.
Start by clarifying the problem constraints and then describe reservoir sampling as the optimal solution. Walk through the algorithm step-by-step, provide Python code, and analyze time and space complexity. Finally, discuss edge cases and potential optimizations.
Pro tip: Mention that reservoir sampling is a classic algorithm used in systems like LinkedIn's feed sampling, and highlight that it guarantees uniformity without knowing the stream length. Also, note that for weighted streams, a variant exists, showing depth.
Confirm that the stream is unbounded, items arrive sequentially, and we need a uniform random sample of size k. Ensure that each item has an equal probability of being in the final sample.
Describe the algorithm: initialize a reservoir of size k with the first k items. For each subsequent item (i-th item, i > k), generate a random integer j between 1 and i. If j <= k, replace the j-th item in the reservoir with the current item.
Write clean Python code using a list for the reservoir and random.randint for sampling. Include a generator-based stream simulation for testing.
State that time complexity is O(n) for n items, as each item is processed once. Space complexity is O(k) for the reservoir. Emphasize that it's a single-pass algorithm.
Cover cases like k=0, k > stream length, and empty stream. Mention extensions like weighted reservoir sampling or distributed sampling if relevant.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.