Maintaining a Random Sample from a Stream of Unknown Length
Data Structure DesignModel answerLast 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 streamget_sample(): returns the current collection of up tokitems
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]:
- See 5 → sample is
[5] - See 10 → sample is
[5, 10] - See 15 → keep each of the 3 items with probability 2/3, so randomly keep 2
- 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
kitems 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a classic streaming algorithm problem. The key insight is that you can maintain a uniform random sample using constant memory by making probabilistic replacement decisions as each item arrives.
Algorithm
Maintain a buffer (the "reservoir") of size k and a counter tracking how many items you've seen:
-
Initial phase (items 1 through k): Place each item directly into the reservoir. No decisions needed since you have room.
-
Replacement phase (item i where i > k):
- Generate a random integer
juniformly from 1 toi - If
j ≤ k, replace the item at positionjin the reservoir with the new item - Otherwise, discard the new item
- Generate a random integer
The elegance is that a single random number makes both decisions: whether to accept the new item (happens when j ≤ k, probability = k/i) and which slot to replace (slot j, uniformly chosen among the k slots).
Correctness Proof
Claim: After processing n items where n ≥ k, each item appears in the reservoir with probability exactly k/n.
For an item at position i where i > k:
- It enters the reservoir at step
iwith probabilityk/i - At each subsequent step
t(fromi+1ton), it survives if:- Either the new item isn't accepted (probability
(t-k)/t), OR - The new item is accepted but picks a different slot (probability
k/t × (k-1)/k = (k-1)/t) - Combined survival probability:
(t-k)/t + (k-1)/t = (t-1)/t
- Either the new item isn't accepted (probability
Multiplying these probabilities:
P(item i in final sample) = k/i × i/(i+1) × (i+1)/(i+2) × ... × (n-1)/n = k/n
For an item at position i where i ≤ k:
- It enters with probability 1
- It must survive steps
k+1throughn, each with probability(t-1)/t
P = 1 × k/(k+1) × (k+1)/(k+2) × ... × (n-1)/n = k/n
Both cases yield k/n, confirming uniform selection.
Implementation
import random
class ReservoirSampler:
def __init__(self, k):
if k < 0:
raise ValueError("k cannot be negative")
self.k = k
self.reservoir = []
self.items_seen = 0
def add(self, item):
self.items_seen += 1
if self.items_seen <= self.k:
# Initial phase: just add to reservoir
self.reservoir.append(item)
else:
# Replacement phase: decide probabilistically
j = random.randint(1, self.items_seen)
if j <= self.k:
# Replace item at position j-1 (converting to 0-indexed)
self.reservoir[j - 1] = item
def get_sample(self):
# Return a copy to prevent external modification
return list(self.reservoir)
Complexity Analysis
- Time per item: O(1) — one random number generation and possibly one assignment
- Space: O(k) — only the reservoir is stored
get_sampletime: O(k) to copy the list
Edge Cases
Fewer than k items: If the stream contains n < k items, the reservoir holds all n items, each with probability 1. This is correct—you can't sample more items than exist.
Empty stream: get_sample() returns an empty list.
k = 0: The algorithm correctly maintains an empty sample (the condition j ≤ 0 never triggers).
Thread safety: This implementation isn't thread-safe. For concurrent streams, use locks or separate samplers per thread with a merge strategy.
Common Mistakes
-
Off-by-one in random range: Using
randint(1, self.items_seen - 1)orrandint(0, self.items_seen)breaks uniformity. The range must be exactly 1 toitems_seeninclusive. -
Two random draws: Separately deciding "do I keep this?" then "what do I replace?" is redundant and more complex. One random draw suffices.
-
Not returning a copy: Returning the reservoir directly allows callers to modify internal state.
-
Wrong probability calculation: Some candidates try
random.random() < k / self.items_seenthen pick a random slot. This works but is less elegant and requires careful handling of the "which slot" logic.
Performance Optimization
For extremely long streams where random number generation is expensive, Algorithm L (Vitter, 1985) computes how many items to skip before the next inclusion. This reduces expected random draws from O(n) to O(k log(n/k)), though each draw requires more computation.
Follow-up Extensions
Weighted sampling: If items have weights, assign each item a key equal to random.random() ** (1/weight) and maintain the k items with the largest keys in a heap. This generalizes to weighted sampling without replacement.
Distributed streams: When data arrives on multiple machines, you can't just merge reservoirs naively (this biases toward machines that saw fewer items). Instead, assign each item a random key and keep the k globally smallest keys, or use a weighted merge that accounts for each machine's total count.