Pattern #37
Reservoir Sampling
ExpertUniform sampling from a stream of unknown length. R-eviction.
When to use
Use when you need a uniform random sample from a stream of unknown length, or sample k items with equal probability without storing the whole stream.
Recognition cues
- Stream of unknown length
- Random sample with equal probability
- Sample k items in one pass
- O(1) space beyond the reservoir
Common pitfalls
- Off-by-one in the acceptance probability (i / k)
- Bias from not using the right random range
- Forgetting that early items must stay in with correct probability
90-second recognition drill
Which pattern fits best?
- Stream of unknown length
- Random sample with equal probability
- Sample k items in one pass
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
pick with probability 1/i
How to think about it
Reservoir sampling draws a uniform random sample of size k from a stream of unknown length in one pass and O(k) space. Algorithm R is the classic: fill the reservoir with the first k items. For the i-th item (i > k), generate a random integer j in [0, i]. If j < k, replace reservoir[j] with item i. The proof: after processing n items, each item is in the reservoir with probability exactly k / n. The acceptance test for item i is k / i; the survival probability for an existing item is 1, 1/i each step, telescoping to k / n.
The pattern extends to randomized data structures: O(1) get-random (LC 380) swaps a picked index with the tail before deleting; weighted sampling (LC 528) uses prefix sums and binary search; rejection sampling (LC 710) maps a uniform draw into the “non-blacklisted” space. For sampling a single random node from a linked list of unknown length (LC 382), k=1 and the same logic applies.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Pick one (k=1) | rand() < 1/i → replace |
LC 382, LC 398 |
| O(1) get-random | Swap-to-tail + delete; hash for O(1) contains | LC 380 |
| Weighted pick | Prefix sum + binary search (alias method) | LC 528 |
| Rejection / blacklist | Map uniform draw into valid index space | LC 710, LC 519 |
Complexity baseline
O(n) time (one pass), O(k) space for the reservoir. Each item: one random number generation and a possible swap. For k=1 the reservoir is a single variable. Get-random structures (LC 380) trade O(n) space for O(1) pick/insert/delete.
From template to problem
- Determine k: pick one, pick k, or weighted.
- Fill the reservoir with the first k items.
- For item i (1-indexed, i > k), draw
j = randInt(0, i). Ifj < k, replacereservoir[j]. - For weighted variants, generate a key per item and maintain the top-k by key.
- The result is the reservoir after the stream ends, each item sampled with probability
k / n.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
/** Reservoir sampling template: Algorithm R, pick k from a stream. */
export class Reservoir<T> {
private reservoir: T[] = [];
private count = 0;
constructor(private k: number) {}
offer(item: T): void {
this.count++;
if (this.count <= this.k) {
this.reservoir.push(item);
return;
}
const j = Math.floor(Math.random() * this.count);
if (j < this.k) this.reservoir[j] = item;
}
sample(): T[] {
return this.reservoir.slice();
}
}/** Reservoir sampling template: Algorithm R, pick k from a stream. */
export class Reservoir<T> {
private reservoir: T[] = [];
private count = 0;
constructor(private k: number) {}
offer(item: T): void {
this.count++;
if (this.count <= this.k) {
this.reservoir.push(item);
return;
}
const j = Math.floor(Math.random() * this.count);
if (j < this.k) this.reservoir[j] = item;
}
sample(): T[] {
return this.reservoir.slice();
}
}- 1#380 Insert Delete GetRandom O(1)Guidemedium
- 2#382 Linked List Random NodeGuidemedium
- 3#398 Random Pick IndexGuidemedium
- 4#519 Random Flip MatrixGuidemedium
- 5#528 Random Pick with WeightGuidemedium
- 6#710 Random Pick with BlacklistGuidehard