Reservoir Sampling
O(n) / O(1) space
Keep the current pick; for the i-th item, replace it with probability 1/i.
0/4 solved
Recognise it
The signal
Uniform random element from a stream or linked list of unknown length, or among matching indices, in one pass, O(1) memory.
1Brute force
Store everything, then sample.
2The observation
O(n) memory: probabilities telescope so each seen item stays with probability k/n.
3Why it works
After i items each one is kept with probability 1/i (k/i for a size-k reservoir): replace the pick with probability 1/i.
Reach for it when
- +uniform pick among matching indices without extra memory
Not when
- ×Sampling must be weighteduse Prefix sums + binary search, or weighted reservoir
- ×Length is known and random access is availableuse Just pick a random index
Practice
- Linked List Random NodeFoundationFoundationMedium
- Random Pick IndexApply it · Uniform among matching indices.Apply itMedium
- Shuffle an ArrayTwists · Related, not reservoir sampling: a uniform permutation (Fisher-Yates) instead of one sample.TwistsMedium
- Love-HateCodeforces2400
Pitfalls
Classic bugs
- !Replacing with a fixed probability like 1/2 each time is not uniform: the i-th item must replace with 1/i.
Looks like it, isn't
- Random Pick with Weight needs Binary Search
Why
Weights known upfront: prefix sums + binary search, not reservoir sampling.
Go deepervariants and techniques · 1 combinations · resources
Combinations
Randomised Sampling Arguments+Sum over Subsets (SOS) DP
find the largest set of items liked by at least half the people, with m <= 60 items but <= 15 liked per person
- Randomised Sampling Arguments:
- a random friend belongs to the optimal half-liked set with probability >= 1/2
- Sum over Subsets (SOS) DP:
- for that friend's <= 15 liked currencies, count supersets over masks