Sub topic 5
Algorithm R: A Reservoir of k Items
The previous chapter kept one random item from a stream. It replaced the current choice with the i-th item (counting from 1) with probability 1/i. This chapter extends that idea to a reservoir of k items. The result is Algorithm R, usually credited to Alan Waterman and popularized by Knuth. It is the standard way to draw a uniform sample of k items, without replacement, from a stream of unknown length.
This chapter assumes you can read Python loops, lists, and iterators, and that you know basic probability: uniform choice, independence, and multiplying probabilities of independent events. The full correctness proof and the cost analysis come in the next two chapters. Here the focus is how the algorithm works, how to implement it, and how it behaves on edge cases.
The Goal Restated
We read items x₀, x₁, x₂, … one at a time. We never know how many will arrive, and we can store only k of them. When the stream ends after n items, we want the k items we hold to be a uniform sample without replacement: every subset of size k is equally likely, so each item ends up in the sample with probability k/n.
If n ≤ k, the answer is simply all the items.
The Two Phases
Algorithm R handles each incoming item in one of two ways.
- Fill phase. The first k items (indices 0 through k − 1) go straight into the reservoir. Every item seen so far is kept, so the reservoir trivially holds a uniform sample of the prefix.
- Replacement phase. For item i, where i ≥ k (0-based), draw a random integer j uniformly from 0 to i inclusive. If j < k, overwrite slot j with the new item. Otherwise discard the new item.
The draw j lands in 0..k − 1 with probability k/(i + 1). So item i enters the reservoir with probability k/(i + 1). Since i + 1 is the number of items seen so far, this is exactly the probability a uniform k-sample of the prefix should give it.
The value of j does two jobs. It decides whether the new item is admitted, and it picks which old item is evicted. Given that the new item is admitted, j is uniform over 0..k − 1, so each current resident is evicted with probability 1/k. That symmetry keeps the old residents equally likely to survive.
Reference Implementation
import random
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i) # inclusive: 0..i
if j < k:
reservoir[j] = item
return reservoirA few details deserve attention:
enumeratestarts at 0, soiis the 0-based index. Itemiis the (i + 1)-th item seen.random.randint(a, b)includes both endpoints. Usingrng.randrange(i + 1)is equivalent. Writingrandint(0, i - 1)orrandrange(i)is a classic off-by-one bug that makes later items too likely to be kept.- The
rngparameter lets you pass a seededrandom.Random(42)for reproducible tests without touching the global generator. streamcan be any iterable: a list, a generator, a file object, or a database cursor. The function reads it exactly once.
Tracing a Small Stream
Take k = 2 and the stream a, b, c, d, e. The table shows one possible run. The "keep probability" column is k/(i + 1).
| i | item | keep probability | j drawn | action | reservoir after |
|---|---|---|---|---|---|
| 0 | a | 1 (fill) | none | append | [a] |
| 1 | b | 1 (fill) | none | append | [a, b] |
| 2 | c | 2/3 | 1 | replace slot 1 | [a, c] |
| 3 | d | 2/4 | 3 | discard | [a, c] |
| 4 | e | 2/5 | 0 | replace slot 0 | [e, c] |
Notice that c was admitted with probability 2/3. It then had to survive item 3 and item 4. At item 3, c is evicted only if j = 1, which has probability 1/4, so it survives with probability 3/4. At item 4 it survives with probability 4/5. Overall:
(2/3) × (3/4) × (4/5) = 2/5 = k/n
The factors telescope. The next chapter turns this pattern into a proof by induction that works for every item and every n.
An Incremental Version
A function that consumes a whole iterable works well for batch jobs. In services, items often arrive through callbacks or message handlers, so you need a sampler that keeps its state between calls. The logic is identical. The only extra state is the count of items seen.
import random
class Reservoir:
def __init__(self, k, rng=None):
if k < 0:
raise ValueError("k must be non-negative")
self.k = k
self.rng = rng if rng is not None else random.Random()
self.seen = 0
self.items = []
def add(self, item):
if self.seen < self.k:
self.items.append(item)
else:
j = self.rng.randrange(self.seen + 1) # 0..seen inclusive
if j < self.k:
self.items[j] = item
self.seen += 1
def sample(self):
return list(self.items)
if __name__ == "__main__":
r = Reservoir(3, rng=random.Random(7))
for word in "the quick brown fox jumps over the lazy dog".split():
r.add(word)
print(r.seen, r.sample())Before add increments the count, self.seen plays the role of i. sample() returns a copy so callers cannot change the internal state by accident.
Edge Cases
Fewer than k items
If the stream has n < k items, the loop never leaves the fill phase. The function returns all n items, which is the only possible sample without replacement. Callers should not assume the result has length k. Check len(result) when that matters.
k = 0
Neither branch ever adds anything. i < 0 is never true, and j < 0 is never true, so the result is an empty list. That is correct, though the loop still reads the whole stream. If you want k = 0 to return immediately, add an early return.
Negative k
The plain function silently returns [] for negative k, which hides a caller bug. The class version raises ValueError. Validate inputs at whichever boundary your code exposes.
Empty stream
The result is [] for any k. No random numbers are drawn.
Duplicate values
Algorithm R samples positions, not distinct values. If the stream contains x three times, the sample may contain x more than once. That is correct sampling without replacement over items. If you need distinct values, you need a different technique, such as sampling over a deduplicated key space.
Order Inside the Reservoir
The set of items in the reservoir is uniform, but their order is not. During the fill phase, item 0 sits in slot 0, item 1 in slot 1, and so on. A short stream with n slightly larger than k will usually return items close to their original order. For example, with k = 3 and n = 4, slot 0 holds x0 unless the single draw at i = 3 happened to be 0.
If your downstream code treats position as meaningful, for example "take the first 10 of the sample as a test set", shuffle the result:
import random
def reservoir_sample_shuffled(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
rng.shuffle(reservoir)
return reservoirThe shuffle costs O(k) and runs once at the end, so it does not change the overall cost.
Why Not Evict the Oldest Item?
A tempting variant admits item i with probability k/(i + 1) but evicts the oldest resident, as in a queue. This breaks uniformity. Older items get evicted first, so recent items are overrepresented in the final sample. Uniform eviction is what lets every resident, old or new, face the same 1/k risk at each admission. The randomness in choosing the slot matters as much as the randomness in the admission decision.
Relationship to the Single-Item Version
Set k = 1. The fill phase keeps item 0. For i ≥ 1, the draw j from 0..i satisfies j < 1 only when j = 0, with probability 1/(i + 1). The only slot is slot 0. This is exactly the warm-up algorithm from the previous chapter, with 1-based i replaced by 0-based i + 1. Algorithm R is the same idea with k slots and a uniformly chosen victim.
Summary of the Working Model
| Quantity | Value for item i (0-based), i ≥ k |
|---|---|
| Probability of admission | k/(i + 1) |
| Probability a given resident is evicted at this step | 1/(i + 1) |
| Probability a given resident survives this step | i/(i + 1) |
| Final inclusion probability for any item | k/n |
Each resident's eviction probability is k/(i + 1) × 1/k = 1/(i + 1). That small fact, multiplied over all later steps, produces the k/n result.
Exercise
With k = 3, item at 0-based index 9 arrives. What is the probability it enters the reservoir, and what is the probability that a specific item currently in slot 2 is evicted at this step?
Show answer
The item enters with probability k/(i + 1) = 3/10. The slot-2 resident is evicted only if j = 2, which has probability 1/10 (equivalently 3/10 × 1/3).
Exercise
A colleague writes j = rng.randrange(i) instead of rng.randrange(i + 1). For k = 1 and a stream of 2 items, what goes wrong?
Show answer
At i = 1, randrange(1) always returns 0, so j < 1 always holds and item 1 always replaces item 0. The sampler returns the last item with probability 1 instead of 1/2. In general, the bug makes later items too likely to be kept.
Exercise
Run reservoir_sample(range(4), 3) mentally. What is the probability that the returned list is exactly [0, 1, 2] in that order, and why does this motivate shuffling?
Show answer
Only one random draw happens, at i = 3, with j uniform over 0..3. If j = 3 (probability 1/4), item 3 is discarded and the result is [0, 1, 2]. In the other cases one slot is overwritten, but the remaining items stay in stream order. Positions reflect arrival order, so shuffle the result if downstream code treats position as meaningful.
Exercise
Modify the Reservoir class so that calling add on an instance with k = 0 does not draw a random number. Show the changed method.
Show answer
Add an early exit: def add(self, item): then self.seen += 1 and return if self.k == 0, otherwise the original logic. For example: if self.k == 0: self.seen += 1; return. The rest of the method stays unchanged, so the result is always empty and no random draws happen.