Elements are streaming past — a giant log file, a live feed, a database cursor you can’t rewind. You must pick one uniformly at random, but you don’t know how many will come and can’t store them all. The trick holds a single slot and a shrinking coin: keep the i-th arrival with probability 1/i. When the stream ends, everyone had an equal shot.
O(n) time · O(1) space · one pass · streaming
stream
Elements arriving one at a time, count unknown, no going back.
reservoir
The one slot you hold — the current pick.
1/i rule
The i-th element replaces the pick with probability 1/i.
uniform
At the end, every element seen is equally likely to be held.
reservoir.js — one slot, a shrinking coin
Ready
A stream of elements arrives one by one. We hold a single reservoir slot. Press Next: the i-th element flips a coin that lands "keep" with probability 1/i — and if it does, it takes the slot.
0
arrived i
–
keep prob 1/i
–
held
How it works
The elegance is that fairness is maintained at every step, not fixed up at the end. The rule looks arbitrary — why 1/i? — but it exactly balances two forces: a new element deserves its fair share now, and every old element must have its share diluted by exactly the right amount to stay equal.
1
First element: always keep
With one element, it’s trivially the pick — keep with probability 1/1 = 1.
2
i-th element: keep with 1/i
Flip a coin weighted 1/i. Heads → it replaces the current pick. Tails → the pick stays.
3
The balance holds
After i elements, each is held with probability exactly 1/i. The new one gets 1/(i+1); each old one keeps its share × the reject chance i/(i+1) — also 1/(i+1).
✓
Stop anytime — still fair
Because it’s balanced every step, you can end the stream at any point and the held element is a uniform pick from all seen so far.
Time
O(n)
Space
O(1)
Passes
1
Needs length?
No
The code
# pick one element uniformly from a stream, O(1) spacedef reservoir_sample(stream):
pick = None
for i, x in enumerate(stream, start=1):
if random.random() < 1 / i: # keep the i-th with prob 1/i
pick = x
return pick
# sample k elements: fill first k, then keep i-th with prob k/i,# replacing a random slot. One pass, O(k) memory.
No length needed, no second pass, no storing the input — which is exactly why it works on infinite or unmeasurable streams where you literally cannot do "pick a random index from 0..n-1".
Quick check
1. Why keep the i-th element with probability exactly 1/i?
Right — the new element gets 1/(i+1), and each old element keeps its 1/i share times the reject chance i/(i+1), which also equals 1/(i+1). Fairness is preserved inductively.
2. What’s the killer advantage over "pick a random index"?
Picking a random index needs to know n and (usually) random access. Reservoir sampling needs neither — one pass, O(1) memory, no length. That’s why it’s the streaming answer.
FAQ
What is reservoir sampling?
A one-pass method to draw a uniform random sample from a stream of unknown or huge length, storing only the sample. For one element: keep the i-th arrival with probability 1/i.
Where is it used?
Random line from a giant file, sampling live logs or click streams, random records from a database cursor, unbiased telemetry sampling — anywhere you can’t store or count the input first.
How do I sample k elements?
Keep the first k, then for each later i-th element keep it with probability k/i, replacing a random one of the k slots. Still one pass, O(k) memory, uniform subset.
Can I do weighted sampling?
Yes — the A-Res / A-ExpJ algorithms extend reservoir sampling to weights, so elements are sampled proportional to weight in one pass. The unweighted 1/i rule is the special case where all weights are equal.
The picture: one slot, seven offers
One run with the draws written out. A highlighted item won its coin flip (a draw of 1 out of i, probability 1/i) and replaced whatever the slot held; a shaded item lost and was forgotten. The row of boxes underneath is the single slot, which is all the memory the algorithm uses.
Worked example, step by step
Stream the numbers 1 to 7 past a one-slot reservoir. At step i, draw an integer from 1 to i; if it is 1 (probability 1/i), replace the slot with the new item. The draws here came from Python’s random.Random(7).randint(1, i), so the run is reproducible.
i
Item
Draw (1..i)
Keep? (needs 1)
Chance to keep
Slot holds
1
1
1
keep
1/1
1
2
2
1
keep
1/2
2
3
3
2
skip
1/3
2
4
4
1
keep
1/4
4
5
5
1
keep
1/5
5
6
6
5
skip
1/6
5
7
7
1
keep
1/7
7
This run ended on 7, but other seeds end elsewhere; what matters is the probability. Item 3 is held after step 3 with probability 1/3. It survives step 4 with probability 3/4, step 5 with 4/5, step 6 with 5/6 and step 7 with 6/7. Multiply: 1/3 × 3/4 × 4/5 × 5/6 × 6/7 = 1/7. The numerators and denominators cancel in a chain, and the same happens for every starting item, so each of the seven ends up with exactly 1/7 (checked with exact fractions). Run 70,000 times with random.Random(2024), the final picks were 10,025 / 10,023 / 9,917 / 9,882 / 10,083 / 10,038 / 10,032 for items 1 to 7, against an expected 10,000 each. The algorithm never knew n = 7 in advance, and could have stopped at any step with a fair pick of everything seen so far.
Complexity and trade-offs
Case
Time
Space
Why
Reservoir sampling, 1 item
O(n)
O(1)
One pass, one random number per element, one slot.
Reservoir sampling, k items (Algorithm R)
O(n)
O(k)
Keep element i with probability k/i, replacing a random slot. Still one pass.
Skip-ahead variants (Algorithm L)
O(k(1 + log(n/k))) expected
O(k)
Draws how many elements to skip instead of one number per element; matters when n ≫ k and random draws are the cost.
Store everything, then random.sample
O(n)
O(n)
Simple, but needs the whole stream in memory.
Random index, when n is known
O(1)
O(1)
Trivially fastest, but needs the length and random access, which a stream or a cursor does not give you.
The cost reservoir sampling pays is randomness, not memory: the basic form makes one random draw per element, which for a very long stream can dominate the work, and that is what the skip-ahead variants remove. What you get in return is the ability to stop anywhere. At every moment the reservoir is a uniform sample of everything seen so far, so a job can be interrupted, or a stream can simply end, without any final correction step.
Common mistakes
Using a constant 1/2
Replacing with probability 1/2 at every step favours late items: over 7 items the last one is picked with probability 1/2 and the first with 1/64. Probabilities are 1/64, 1/64, 1/32, 1/16, 1/8, 1/4, 1/2 for items 1 to 7. The rate has to fall as 1/i to stay fair.
Off-by-one in the denominator
Using 1/(i+1) with a 1-based i gives every item 1/8 on a 7-item stream. The sample is uniform but short of probability: with chance 1/8 the slot is never filled and you return nothing. With a 0-based loop index, use randint(0, i) and keep on 0.
Always replacing in the k-item version
Picking a random slot and overwriting it unconditionally means the final element is always in the sample, with probability 1 rather than k/n. The replacement must be gated by the k/i test first, and only then a slot chosen at random.
Merging shard samples without weights
If two workers each keep a uniform sample of their shard, concatenating the two samples is biased whenever the shards differ in size: items from the small shard are over-represented. Merge by drawing from each sample in proportion to the number of items its shard saw.
Seeding every worker identically
With a fixed seed, parallel jobs make the same sequence of draws and pick items at the same positions. That is reproducible, but not independent. Seed once per run and store the seed, rather than hard-coding it in the library.
Where this shows up
Random line from a huge file
The one-pass way to choose a uniform random line without counting lines first is to read once and replace the pick with probability 1/i at line i, which is the classic form of this algorithm.
Database statistics
PostgreSQL’s ANALYZE samples table rows with a reservoir method (Vitter’s) to build the statistics the query planner uses, since a sample of fixed size is enough however big the table is.
Linked lists and cursors
“Linked List Random Node” asks for a random node from a list whose length you do not know, with O(1) extra space: this algorithm exactly.
Sampling live traffic
Keeping a bounded, unbiased sample of events from an unbounded log or request stream for debugging or monitoring uses the k-item form: memory stays at k however long the service has been up.
SOLVE IT YOURSELF
Solve it: sample a stream you can’t measure
Pick one item uniformly at random from a stream whose length you do not know, storing exactly one item. It sounds impossible; it is six lines. Python or TypeScript, running for real in your browser.
YOUR TASK
Implement sample_one(stream, rand) — one uniformly-random item using O(1) memory — and sample_k(stream, k, rand) for a reservoir of size k. rand(n) returns an integer in [0, n) and is injected, so results are deterministic and testable.
HINTS — 5 IDEAS
For a single item: at index i (0-based), replace the held item with probability 1/(i+1) — i.e. when rand(i + 1) == 0.
Why it is uniform: item i is kept with probability 1/(i+1), then survives every later step with probability i+1/i+2 · i+2/i+3 · … — the product telescopes to exactly 1/n.
For a reservoir of k: fill it with the first k items outright.
After that, for item i, draw j = rand(i + 1) and overwrite slot jonly ifj < k. That happens with probability k/(i+1), which is exactly right.
Nothing here needs the stream length in advance, and nothing is stored beyond the reservoir — which is the entire point.
CPython · WebAssembly✓ Solved
1
1
▶ Watch it explained
Reservoir Sampling: Time and Space Complexity, From First Principles