Stream Sampling with Fixed Memory
Statistics & ExperimentsModel answerLast 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires reservoir sampling, a classic streaming algorithm that maintains a fixed-size uniform random sample from an unbounded stream.
Solution for k = 1
When maintaining a single-element sample:
- Keep the first element
- When element i arrives (i > 1), replace the current sample with element i with probability 1/i
This ensures that after seeing n elements, each has probability 1/n of being selected.
Proof: By induction. After element 1, it's selected with probability 1. Assume after i-1 elements, each has probability 1/(i-1). When element i arrives:
- Element i is selected with probability 1/i
- Each prior element remains selected with probability (1/(i-1)) × (1 - 1/i) = (1/(i-1)) × ((i-1)/i) = 1/i
Solution for arbitrary k
Maintain an array (the "reservoir") of size k:
- Fill the reservoir with the first k elements
- For element i where i > k:
- Generate a random integer j uniformly in [1, i]
- If j ≤ k, replace reservoir[j-1] with element i
- Otherwise, discard element i
Proof of correctness: After processing n elements (n ≥ k), we show each element has probability k/n of being in the reservoir.
For element i where i ≤ k: It starts in the reservoir and remains there only if never replaced. The probability it's never chosen for replacement is:
∏(t=k+1 to n) P(not replaced at step t) = ∏(t=k+1 to n) (1 - 1/t) = ∏(t=k+1 to n) ((t-1)/t) = k/n
For element i where i > k: It enters with probability k/i, then survives subsequent replacements:
P(selected) = (k/i) × ∏(t=i+1 to n) (1 - 1/t) = (k/i) × ((i)/(n)) = k/n
Implementation
import random
def reservoir_sample(stream, k):
"""
Sample k elements uniformly from a stream.
Args:
stream: Iterator of elements
k: Sample size
Returns:
List of k sampled elements (or fewer if stream has < k elements)
"""
reservoir = []
for i, element in enumerate(stream, start=1):
if i <= k:
# Fill reservoir with first k elements
reservoir.append(element)
else:
# With probability k/i, replace a random reservoir element
j = random.randint(1, i)
if j <= k:
reservoir[j - 1] = element
return reservoir
Complexity Analysis
Time: O(1) per element
- Each element requires one random number generation and at most one array write
Space: O(k)
- Only the reservoir array is maintained
Random draws: One per element after the first k elements
Edge Cases and Common Mistakes
-
Stream shorter than k: The reservoir correctly contains all elements seen; no special handling needed
-
Off-by-one errors: The random range must be [1, i], not [0, i-1] or [1, i+1]. Mapping to zero-indexed arrays requires care
-
Randomness scope: Each decision must use a fresh random number; reusing the same value breaks uniformity
-
Index vs count: When element i arrives, i is the total count including that element
-
Probability interpretation: "With probability k/i" means generating j ∈ [1, i] and checking if j ≤ k, which naturally gives the correct probability
Stronger Properties
The algorithm not only ensures each element has probability k/n, but actually guarantees that every possible k-subset of the n elements is equally likely—there are C(n,k) such subsets, each with probability 1/C(n,k). This follows from the sampling-without-replacement property.
Practical Considerations
- For distributed streams, partition the stream, sample from each partition, then combine reservoirs with weighted sampling
- For weighted sampling, use Algorithm A-Res or priority-based reservoir sampling
- The algorithm maintains validity at every step, not just when the stream ends—useful for real-time queries