KatInterview

Stream Sampling with Fixed Memory

Statistics & ExperimentsModel answer
MediumModel answerStatistics & Experimentsprobabilitystreaming-algorithmssampling

Last updated

Maintain a uniformly random sample of k elements from an unbounded stream in one pass using O(k) space.

You receive elements one at a time from a data stream of unknown and potentially unbounded length. Your task is to maintain a sample of exactly k elements such that, at any point after seeing n elements (where n ≥ k), each element has an equal probability k/n of being in your current sample.

Design an algorithm that:

  • Processes each element in one pass (no revisiting)
  • Uses memory proportional to k, not to the stream length
  • Produces a uniformly random sample without replacement
  • Has access to a uniform random number generator

Begin by solving the problem for k = 1, then extend your solution to arbitrary k.

Constraints

  • The stream length n is unknown in advance and may exceed available memory
  • Only one pass through the stream is permitted
  • Memory usage must be O(k)
  • If fewer than k elements arrive, return all elements seen

Follow-up Questions

  • Prove that your algorithm maintains the correct probability k/n for each element
  • What are the time and space complexities per element?
  • How many random numbers does your algorithm generate per element?
  • What edge cases require special handling?

Hints

Hint 1

For k=1, think about what probability you should keep each new element with to maintain uniform selection

Hint 2

When element i arrives, it should have probability k/i of being in the sample—how does this inform your acceptance rule?

Hint 3

If you accept a new element into a full sample, which existing element should you replace?