KatInterview

Maintaining a Random Sample from a Stream of Unknown Length

Data Structure DesignModel answer
MediumModel answerData Structure Designreservoir-samplingstreaming-algorithmsrandomized-algorithms

Last updated

Implement a data structure that keeps k randomly chosen items from a stream where you don't know the total count ahead of time.

You're building a system that processes a continuous stream of data items. You need to maintain a collection of exactly k randomly selected items from everything you've seen so far, but you don't know how many items the stream will contain—it might even be infinite.

Your solution must guarantee that at any point, each item seen so far has an equal chance of being in your collection.

Requirements

Implement a class with these methods:

  • Constructor: accepts k, the number of items to maintain
  • add(item): processes one new item from the stream
  • get_sample(): returns the current collection of up to k items

Constraints

  • You cannot store all items—memory must be O(k)
  • Each item is processed exactly once as it arrives
  • Processing each item should take O(1) time
  • Every item must have equal probability of selection

Example Walkthrough

With k = 2 and stream [5, 10, 15, 20]:

  1. See 5 → sample is [5]
  2. See 10 → sample is [5, 10]
  3. See 15 → keep each of the 3 items with probability 2/3, so randomly keep 2
  4. See 20 → keep each of the 4 items with probability 2/4 = 1/2, so randomly keep 2

After processing all 4 items, each must appear in the final 2-item sample with probability exactly 1/2.

Questions to Consider

  • What happens when fewer than k items have arrived?
  • How do you decide whether to keep a new item?
  • If you keep a new item, which existing item should you remove?
  • Can you prove your algorithm gives each item equal probability?

Hints

Hint 1

For the first k items, you have room for all of them—no decisions needed yet.

Hint 2

When item number n arrives (where n > k), think about what probability it should have of being in your sample. Then use one random number to make both decisions: whether to include it AND what to replace.

Hint 3

The probability that item i ends up in the final sample is k/n. This should be true after processing any number of items n ≥ k.