Short answer: Reservoir sampling draws k items uniformly from a stream of unknown length. The first k items fill the reservoir. When item i arrives, with i counted from 1, it replaces a random reservoir slot with probability k/i. Algorithm R uses one random number per item and O(k) memory. At every prefix of the stream, the reservoir is a uniformly random subset of the items seen so far.
What the problem actually asks
If the stream length n were known, each item could be kept with an inclusion decision in a combination. The length is not known, and the stream may not be rewound. The invariant that saves the algorithm is stronger than the final distribution: after i items, every subset of size k is equally likely. The replacement probability k/i is exactly what maintains that invariant when item i is considered.
A naive policy that keeps each item with probability k/n cannot be run without n. A policy that always keeps the first k items ignores the tail.
What the algorithm guarantees
After n items the reservoir is equally likely to be any k-subset, provided each random test is independent and uniform. Time is Θ(n) and memory is Θ(k), which does not grow with n. The algorithm sees each item once. Weighted reservoir sampling, where items have unequal probabilities, is a different formula. Algorithm R is the unweighted subset.
The index arithmetic is the usual off-by-one hazard. If i starts at 0, the probability k/i is nonsense on the first item. Count i from 1, or use the equivalent test with a zero-based count of items already seen.
The working steps
- Put the first k items into the reservoir. If the stream ends earlier, the reservoir is the whole stream.
- For each later item, let i be its 1-based index. With probability k/i, replace a uniformly chosen reservoir slot by this item. Otherwise discard it.
- Continue until the stream ends. Do not rewind.
- The proof invariant is that every k-subset of the first i items is equally likely. The probability k/i is the one that preserves it.
- For a sample of size 1, the rule reduces to replacing the stored item with probability 1/i.
Uniformity is over subsets of the items seen so far, unweighted. A weighted stream, a sliding window, or a sample that must be stable under deletions needs a different algorithm. Fisher-Yates permutes an array that is already in memory and can then take a prefix. The reservoir is what remains when the array does not fit or has not ended.
Approaches that look simpler and fail
| Approach | Why it fails when every new item replaces a slot with probability k over n |
|---|---|
| Use probability k/n before the stream ends | n is unknown. Using the current length is the algorithm. Using a guessed n biases the sample toward the head or the tail. |
| Always replace a random slot | Late items then dominate. The replacement probability has to fall as 1/i. |
| Keep the first k items and ignore the rest | The sample is deterministic and misses every subset that intersects the tail. |
| Count i from 0 and divide by i | The first probability is undefined. The 1-based index, or an equivalent formulation, is part of the invariant. |
A uniform permutation of a finite array is Fisher-Yates. A weighted sample is a different reservoir formula. Algorithm R is the unweighted stream subset of size k.
A working example
This Python fragment keeps a reservoir of size 2. At 1-based index i an arriving item replaces one stored item with probability 2/i. The seeded sample is a 2-subset. A second loop checks that, across trials, no item is starved. It prints the one sample 2 4.
import random
def sample(rng, stream, k):
reservoir = []
for i, item in enumerate(stream, 1):
if len(reservoir) < k:
reservoir.append(item)
elif rng.randrange(i) < k:
reservoir[rng.randrange(k)] = item
return reservoir
one = sample(random.Random(1), [0, 1, 2, 3, 4], 2)
assert len(one) == 2 and len(set(one)) == 2
counts = [0] * 5
for t in range(3000):
for item in sample(random.Random(t), [0, 1, 2, 3, 4], 2):
counts[item] += 1
assert all(abs(c - 1200) < 200 for c in counts)
print(*one)
Where it is used
Reservoir sampling keeps a uniform sample of a log or a query stream in one pass, when the length is not known in advance. Spark-style stream samples use that reservoir. A sample that first counts the records needs a second pass.
When you can drop this algorithm
Drop a two-pass method when the stream cannot be rewound. Keep algorithm R, with probability k/i at the i-th item.
Why this stays published
We publish this so a search for reservoir sampling returns the replacement probability k/i and the invariant that every prefix stays uniform. Reservoir sampling keeps a uniform k-subset of a stream by replacing a stored item with probability k/i when the i-th item arrives.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
