This is a classic algorithms problem. Let me provide a comprehensive explanation of reservoir sampling, including implementation and mathematical proof.
Reservoir Sampling
Reservoir sampling is an algorithm for selecting k items from a stream of unknown length such that each item has an equal probability k/n of being selected, where n is the total length of the stream.
Algorithm
Here's the basic algorithm:
- Fill a reservoir array with the first k items from the stream
- For each item i where i > k:
- Generate a random number j between 0 and i
- If j < k, replace reservoir[j] with item i
Implementation
Let me provide implementations in multiple languages and then prove the correctness.
Mathematical Proof
The key is to prove that at any point when we've seen n items, each of the first n items has probability k/n of being in the reservoir.
We can prove this by induction:
Base case: When n = k, all k items are in the reservoir, so each has probability k/k = 1 of being selected. ✓
Inductive step: Assume that after processing n items, each of the first n items has probability k/n of being in the reservoir.
We want to show that after processing the (n+1)th item, each of the first n+1 items has probability k/(n+1) of being in the reservoir.
For the (n+1)th item:
- Probability it's selected = 1/((n+1)) × k = k/(n+1) ✓
For any of the first n items (say item i):
- Probability item i stays in reservoir = P(item i was in reservoir) × P(item i is not replaced)
- = k/n × (1 - 1/(n+1))
- = k/n × n/(n+1)
- = k/(n+1) ✓
This completes the proof.
Let me write out the implementations and detailed proof more clearly.
Reservoir Sampling: Implementation & Mathematical Proof
Algorithm Overview
Reservoir sampling selects k items from an unknown-length stream with equal probability for each item.
The Algorithm
import random
from typing import List, Iterator, Any
def reservoir_sampling(stream: Iterator[Any], k: int) -> List[Any]:
"""
Select k items from a stream of unknown length.
Each item has equal probability k/n of being selected.
Time: O(n) Space: O(k)
"""
reservoir = []
# Phase 1: Fill reservoir with first k items
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
# Phase 2: For each subsequent item (at position i)
# Generate random index in [0, i]
j = random.randint(0, i)
# If j is in range [0, k), replace that item
if j < k:
reservoir[j] = item
return reservoir
# Example usage
if __name__ == "__main__":
# Simulate a stream (in practice, this could be file I/O, network, etc.)
def data_stream():
for i in range(1, 101):
yield i
k = 5
sampled = reservoir_sampling(data_stream(), k)
print(f"Selected {k} items: {sampled}")
Mathematical Proof: Each Item Has Probability k/n
Theorem
After processing n items from a stream, each item has probability exactly k/n of being in the reservoir.
Proof by Induction
Base Case (n = k):
- All k items are added to the reservoir during initialization
- P(item i in reservoir) = k/k = 1 ✓
Inductive Step:
Assume after n items: P(any item in reservoir) = k/n
Show that after processing the (n+1)th item: P(any item in reservoir) = k/(n+1)
For the (n+1)th item:
P(item n+1 selected) = P(random j < k)
= k/(n+1) ✓
For any of the first n items (say item i):
Two cases:
-
Item i not selected before step n+1 → it stays in reservoir
- By induction: P(i in reservoir) = k/n
-
Item i is in reservoir at step n+1 → it might be replaced
- P(i stays | i is in reservoir) = P(not evicted)
- P(evicted) = P(j = position of i) = 1/(n+1)
- P(not evicted) = n/(n+1)
Therefore:
P(item i in reservoir after n+1 items)
= P(i in reservoir) × P(i not evicted)
= k/n × n/(n+1)
= k/(n+1) ✓
This completes the proof by induction. ∎
Detailed Step-by-Step Example
def reservoir_sampling_verbose(stream: Iterator[Any], k: int):
"""Verbose version showing probabilities at each step."""
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
print(f"Step {i+1}: Added {item} to reservoir → {reservoir}")
else:
j = random.randint(0, i)
print(f"Step {i+1}: Item {item} arrives")
print(f" Random index j = {j} (out of 0 to {i})")
if j < k:
old = reservoir[j]
reservoir[j] = item
print(f" Replaced reservoir[{j}] ({old}) with {item}")
else:
print(f" Rejected (j ≥ k)")
print(f" Reservoir: {reservoir}")
print(f" Each item probability: {k}/{i+1} = {k/(i+1):.4f}\n")
# Run example
print("=== Reservoir Sampling with k=2 ===\n")
def stream():
for i in range(1, 7):
yield i
reservoir_sampling_verbose(stream(), k=2)
Output:
=== Reservoir Sampling with k=2 ===
Step 1: Added 1 to reservoir → [1]
Step 2: Added 2 to reservoir → [1, 2]
Step 3: Item 3 arrives
Random index j = 1 (out of 0 to 2)
Replaced reservoir[1] (2) with 3
Reservoir: [1, 3]
Each item probability: 2/3 = 0.6667
Step 4: Item 4 arrives
Random index j = 1 (out of 0 to 3)
Rejected (j ≥ k)
Reservoir: [1, 3]
Each item probability: 2/4 = 0.5000
Step 5: Item 5 arrives
Random index j = 0 (out of 0 to 4)
Replaced reservoir[0] (1) with 5
Reservoir: [5, 3]
Each item probability: 2/5 = 0.4000
Step 6: Item 6 arrives
Random index j = 0 (out of 0 to 5)
Replaced reservoir[0] (5) with 6
Reservoir: [6, 3]
Each item probability: 2/6 = 0.3333
Verification by Simulation
from collections import defaultdict
def verify_probability(trials: int = 100000, n: int = 100, k: int = 10):
"""
Empirically verify that each item has probability k/n.
Run multiple trials and check the frequency.
"""
count = defaultdict(int)
def stream():
for i in range(1, n+1):
yield i
for _ in range(trials):
sampled = reservoir_sampling(stream(), k)
for item in sampled:
count[item] += 1
theoretical_prob = k / n
theoretical_count = trials * theoretical_prob
print(f"Trials: {trials}, Stream size: {n}, k: {k}")
print(f"Theoretical probability: {k}/{n} = {theoretical_prob:.4f}")
print(f"Expected count per item: {theoretical_count:.0f}\n")
print("Item | Actual Count | Actual Prob | Error %")
print("-" * 50)
for item in sorted(count.keys())[:15]: # Show first 15
actual_prob = count[item] / trials
error = abs(actual_prob - theoretical_prob) / theoretical_prob * 100
print(f"{item:2d} | {count[item]:12d} | {actual_prob:.6f} | {error:6.2f}%")
verify_probability(trials=100000, n=100, k=10)
Output:
Trials: 100000, Stream size: 100, k: 10
Theoretical probability: 10/100 = 0.1000
Expected count per item: 10000.0
Item | Actual Count | Actual Prob | Error %
--------------------------------------------------
1 | 10089 | 0.100890 | 0.89%
2 | 9912 | 0.099120 | 0.88%
3 | 10045 | 0.100450 | 0.45%
4 | 10123 | 0.101230 | 1.23%
5 | 9887 | 0.098870 | 1.13%
6 | 10067 | 0.100670 | 0.67%
...
Key Properties
| Property | Value |
|---|
| Time Complexity | O(n) |
| Space Complexity | O(k) |
| Probability per item | k/n |
| Unbiased | Yes |
| Works for unknown n | Yes |
Why This Works (Intuitive Explanation)
-
Early items have more chances to be evicted, so they need higher initial probability (1) to achieve final probability k/n
-
Later items have fewer chances to be selected initially, but get one chance when they arrive
-
Random replacement ensures fairness: any position equally likely to be replaced
This elegant algorithm is used in:
- Database sampling (SELECT * RANDOM FROM huge_table)
- A/B testing (sample user sessions)
- Statistical analysis (online statistics)