Algorithms · Visualized
Random: Reservoir Sampling
Randomized Algorithms
Randomness as a tool — shuffles, sampling, and probabilistic selection.
Selects a random sample of k items from a stream of unknown or very large size, using only O(k) memory and a single pass — impossible to do with normal random sampling since you don't know the total size in advance. Time: O(n) average, O(n) worst; space: O(k) — only the reservoir is stored, regardless of stream size.
Big-O: Expected-case guarantees with simple implementations.
Reservoir Sampling
Randomized AlgorithmsSelects a random sample of k items from a stream of unknown or very large size, using only O(k) memory and a single pass — impossible to do with normal random sampling since you don't know the total size in advance. Each new item gets a shrinking probability of replacing an existing item in the sample as the stream grows.
How Reservoir Sampling Works
- Fill an initial 'reservoir' array with the first k items from the stream directly.
- For each subsequent item (the i-th item, where i > k), generate a random integer j between 0 and i (inclusive).
- If j is less than k, replace the item at index j in the reservoir with this new item.
- If j is k or greater, discard this new item and keep the reservoir as is.
- After processing the entire stream, the reservoir contains a uniformly random sample of k items from everything seen.
Reservoir Sampling Worked Example
Input: {stream: [10, 20, 30, 40, 50], k: 2}
Reservoir starts as [10,20] (first 2 items). Item3(30), i=2(0-indexed from k): random j in[0,2], say j=1 → replace reservoir[1] with 30 → [10,30]. Item4(40), random j in[0,3], say j=3 (≥k) → discard, no change. Item5(50), random j in[0,4], say j=0 → replace reservoir[0] with 50 → [50,30]. Final random sample of size 2: [50,30] (one of many equally likely outcomes).
import random
def reservoir_sample(stream, k):
# keep the first k items
reservoir = [next(stream) for _ in range(k)]
for i, item in enumerate(stream, start=k):
j = random.randint(0, i)
if j < k:
reservoir[j] = item
return reservoirBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Reservoir Sampling Time & Space Complexity
When to Use Reservoir Sampling
- Sampling from massive or infinite data streams (e.g. log lines, live sensor feeds) where the total count isn't known in advance and full storage is impossible.
- A/B testing and random survey sampling from continuously arriving data.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.