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 Algorithms

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. Each new item gets a shrinking probability of replacing an existing item in the sample as the stream grows.

How Reservoir Sampling Works

  1. Fill an initial 'reservoir' array with the first k items from the stream directly.
  2. For each subsequent item (the i-th item, where i > k), generate a random integer j between 0 and i (inclusive).
  3. If j is less than k, replace the item at index j in the reservoir with this new item.
  4. If j is k or greater, discard this new item and keep the reservoir as is.
  5. 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).

Random: Reservoir SamplingO(n)
Uniform sample of k from a stream.
10
0
20
1
30
2
40
3
50
4
reservoir[10, 20]
Step 1 / 7
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Reservoir Sampling: seed with the first 2 items, then replace each later item with probability k/i.
Python · Randomized Algorithms in Code
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 reservoir

Behind 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

BestO(n) — must see the whole stream once
AverageO(n)
WorstO(n)
SpaceO(k) — only the reservoir is stored, regardless of stream size

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.