Sub topic 2
Algorithm R: A Reservoir of k Items
This chapter assumes you know basic Python, conditional probability, Big-O notation, and proof by induction. It extends the one-item reservoir to k items.
The Algorithm
Store the first k items. When item i arrives (0-based, i >= k), draw j uniformly from 0..i. If j < k, overwrite slot j with the new item.
import random
from collections import Counter
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 reservoir
# Empirical check: each item should appear with frequency close to k/n
trials = 100_000
counts = Counter()
for _ in range(trials):
for x in reservoir_sample(range(10), 3):
counts[x] += 1
for x in range(10):
print(x, counts[x] / trials) # each should be close to 3/10 = 0.3Each new item enters with probability k/(i+1). If it enters, it evicts one current resident chosen uniformly at random.
Proving Every Item Has Probability k/n
Use 1-based positions here. Claim: after t ≥ k items, each item seen so far is in the reservoir with probability k/t.
- Base case (t = k): every item is stored, so each has probability 1 = k/k.
- Step (t → t+1): item t+1 enters with probability k/(t+1). An item already in the reservoir is evicted only if the new item enters and picks its slot, which has probability (k/(t+1))·(1/k) = 1/(t+1). The item survives with probability t/(t+1). So its probability of being in the reservoir becomes (k/t)·(t/(t+1)) = k/(t+1).
At t = n, every item is present with probability k/n.
Cost Analysis
| Resource | Cost |
|---|---|
| Time | O(n), one pass |
| Space | O(k) |
| Random numbers | n − k, one per item after the first k |
| Expected replacements | Σ from i=k+1 to n of k/i ≈ k·ln(n/k) |
Replacements get rarer as the stream grows, but Algorithm R still draws a random number for every item. Algorithm L, covered later, removes that cost.
Checking Uniformity Empirically
The test loop above runs the sampler 100,000 times on a stream of 10 items with k = 3. With this many trials, each frequency should land within about ±0.005 of 0.3. A consistent drift points to a bug, such as using randint(0, i - 1). For a formal test, apply a chi-squared test to the counts.
Exercise
With k = 10 and a stream of n = 1,000,000 items, roughly how many times does Algorithm R overwrite a reservoir slot?
Show answer
About k·ln(n/k) = 10·ln(100,000) ≈ 10 × 11.5 ≈ 115 replacements, even though it makes 999,990 random draws.
Exercise
In the inductive step, why does an item already in the reservoir survive with probability t/(t+1)?
Show answer
It is evicted only when the new item is accepted (probability k/(t+1)) and the new item picks its slot (probability 1/k). Eviction therefore has probability 1/(t+1), and survival has probability 1 − 1/(t+1) = t/(t+1).