Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Advanced & Niche/Reservoir Sampling

Learn the pattern · ~14 min

Reservoir Sampling

also called Algorithm R

Keep one pick; let the i-th item take over with probability 1/i. Every item ends up equally likely, without storing the stream or knowing its length.

Signalsrandom element from a linked list/stream of unknown sizeuniform pick among matching indices without extra memory
Cheat sheet and practice

Reach for it when you read

  • +Pick a uniformly random item from a stream or linked list of unknown length in one pass.
  • +O(1) extra space is required, so you can't copy the items into an array.
  • +Pick a random index among the items that match a target, without storing them.
  • +Keep a random sample of k items from a stream too big to store.

Not this one when

  • ×Items with known weights: prefix sums and binary search.
  • ×A set that changes between picks with O(1) getRandom: an array plus an index map.
  • ×A random order of the whole array: Fisher–Yates shuffle.

Learn Reservoir Sampling

First, what are we trying to do?

Pick one item uniformly at random: every item must have the same chance. From 5 items, each must come out with chance 1/5.

That's easy when you can see them all: roll a number from 1 to 5. The hard version is a stream: items go past one at a time, you read each once, and you don't know how many there are until it ends. You can't roll "1 to n" when you don't know n.

Reservoir sampling solves it with one slot, the reservoir, that holds a current candidate. When the stream ends, the candidate is the answer.

How do we keep the candidate fair?

Take the stream 7, 3, 9, 4, 6. The rule is one line:

The i-th item replaces the candidate with chance exactly 1/i.

So the 1st item is always taken, the 2nd with chance 1/2, the 3rd with chance 1/3, and so on. Here's what that does to the chances:

i item what happens chance each item so far is the candidate
1 7 taken for sure: it's the only one 7: 1
2 3 takes over with chance 1/2; else 7 stays 7: 1/2, 3: 1/2
3 9 takes over with chance 1/3; else the old candidate stays 7, 3, 9: 1/3 each
4 4 takes over with chance 1/4 7, 3, 9, 4: 1/4 each
5 6 takes over with chance 1/5 all five: 1/5 each

Read the last column: after every step, all the items seen so far are equally likely. When the stream ends, that's the fair pick we wanted, without knowing the length.

The code for it

C++
int pick(const vector<int>& stream) {
    int candidate = 0, i = 0;                  // i = items seen so far
    for (int x : stream) {
        i++;
        if (rng() % i == 0) candidate = x;     // chance 1/i; the first item always wins
    }
    return candidate;
}

You don't need to memorise this. It's the table: count the items, and let item i win with chance 1/i.

Why does rng() % i == 0 mean "chance 1/i"? rng() % i is one of the i numbers 0, 1, …, i − 1, all (almost exactly) equally likely, and one of them is 0. Use mt19937, not rand(): RAND_MAX can be as small as 32,767, so once i passes that, rand() % i can never land on some values and the chances go wrong.

Fine, but how does this help us?

The classic problem: Linked List Random Node. Return a random node's value from a linked list, each node equally likely. The follow-up: the list is huge, its length unknown, and you may use only O(1) extra space.

For 7 → 3 → 9 → 4 → 6, by hand, as if you could see the whole list:

step what you do result
1 walk the list and count 5 nodes
2 roll a number from 1 to 5 say 2
3 walk again to node 2 value 3

Every roll from 1 to 5 has chance 1/5, so every value 7, 3, 9, 4, 6 comes out with chance 1/5. That's the target.

The brute force

Copy the values into an array, then pick a random index.

C++
int getRandomBrute(ListNode* head) {
    vector<int> vals;
    for (ListNode* p = head; p != nullptr; p = p->next)
        vals.push_back(p->val);                // a copy of the whole list
    return vals[rng() % vals.size()];
}

It's correct, and at LeetCode's 10⁴ nodes it passes. But it stores the whole list: O(n) extra memory, which the follow-up forbids. For 10⁹ nodes that's 4 GB of ints. Counting first and walking again saves memory but reads the list twice; a stream can be read once.

The one thought that fixes it

You don't need the final length. You only need this to stay true: after i items, the candidate is each of them with chance 1/i.

Stop at step 3, when the 9 arrives. Right now the candidate is 7 or 3, with chance 1/2 each.

  • The 9 takes over with chance 1/3.
  • Otherwise, with chance 2/3, the old candidate stays. So the 7 is still there with chance 1/2 × 2/3 = 1/3, and the 3 too.

All three at 1/3. Now follow the 3 through the whole stream: it must be taken at step 2, then survive every later step:

i item chance item i takes over chance the 3 survives this step
1 7 1
2 3 1/2 taken: 1/2
3 9 1/3 2/3
4 4 1/4 3/4
5 6 1/5 4/5

1/2 × 2/3 × 3/4 × 4/5 = 1/5. Each top cancels the bottom before it. For item j in a stream of n, it's (1/j) × (j/(j+1)) × … × ((n−1)/n) = 1/n, whatever j is.

The short proof, one step at a time: say that after i − 1 items each is the candidate with chance 1/(i−1). Item i takes over with chance 1/i, so it has 1/i. Every earlier item survives with chance (i−1)/i, so it has 1/(i−1) × (i−1)/i = 1/i. True after i items too. It starts true (1 item, chance 1), so it holds at every step, and at the end.

C++
int getRandom(ListNode* head) {
    int candidate = 0, i = 0;
    for (ListNode* p = head; p != nullptr; p = p->next) {
        i++;                                   // p is the i-th node
        if (rng() % i == 0) candidate = p->val;   // take over with chance 1/i
    }
    return candidate;
}

Dry run

One real run of the code on 7 → 3 → 9 → 4 → 6, with mt19937 rng(4):

i value rng() % i take over? candidate
1 7 0 yes 7
2 3 0 yes 3
3 9 1 no 3
4 4 1 no 3
5 6 4 no 3

This run returns 3. One run proves nothing about chances. The proof above gives exactly 1/5 each, and a simulation agrees: in 10⁵ runs (seed 1) each value came up between 19,855 and 20,238 times, close to 20,000. That's what the brute force gives, with one pass and no copy.

Why it's O(n) and O(1)

Count what happens to each node: it's visited once, with one random number and one comparison. That's O(n) time. The state is two integers and a pointer, whatever the length: O(1) extra space.

From an O(n) copy down to O(1) space, by keeping the "fair so far" promise one item at a time.

Only some items count? Count only the matches

Random Pick Index: return a random index where nums[j] == target. Run the same reservoir, but i counts only the matches:

C++
if (nums[j] != target) continue;       // only matches count
if (rng() % ++i == 0) ans = j;

On [1, 2, 3, 3, 3] with target 3, the indices 2, 3, 4 each come out with chance exactly 1/3, by the same argument over three matches.

Keep k items? k slots

To pick k items fairly, fill the first k slots, then let item i (from k + 1 on) replace a random slot with chance k/i:

C++
i++;
if (i <= k) res.push_back(x);              // the first k fill the slots
else {
    unsigned r = rng() % i;                // 0 .. i-1
    if (r < (unsigned)k) res[r] = x;       // chance k/i; it replaces slot r
}

Each item ends up kept with chance k/n. On our stream with k = 2, every value is kept with chance exactly 2/5 (we counted all 3 × 4 × 5 = 60 roll sequences).

A whole random order: Fisher–Yates

Shuffle an Array needs every order equally likely. Walk from the back and swap each position with a random one at or before it:

C++
for (int i = a.size() - 1; i > 0; i--)
    swap(a[i], a[rng() % (i + 1)]);            // a[i] gets a random one of a[0..i]

For [1, 2, 3] there are 3 × 2 = 6 roll pairs and each gives a different order, so each order has chance exactly 1/6. Note i + 1: a[i] may stay where it is.

Remember this

  • "A uniform random item, one pass, length unknown, O(1) space": reservoir sampling.
  • Item i takes over with chance 1/i. Start i at 1, so the first item is always taken.
  • Use mt19937, not rand().
  • Random with weights is not a reservoir: build prefix sums and binary search with lower_bound.
  • Whenever a problem asks for "pick fairly from something you can only walk once", it's a reservoir.

Practise it on Linked List Random Node, then Random Pick Index (only matches count), Shuffle an Array (a whole random order), Random Pick with Weight (weights: not a reservoir) and Insert Delete GetRandom O(1) (a set that keeps changing).

Below, watch Linked List Random Node run line by line.

Watch it work, line by line

Linked List Random Node ↗, stream = 4 → 7 → 1 → 9 → each value with probability 1/4 (10,000 picks: about 2,500 each). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Do I need a uniform random pick from something I can only walk once, without knowing how long it is or storing it?

Reach for it when

  • +random element from a linked list/stream of unknown size
  • +uniform pick among matching indices without extra memory
  • +O(1) or O(k) memory

It fails 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

Looks like it, isn't (and the other way round)

  • Random Pick with Weight looks like Reservoir Sampling, needs Binary Search

    Weights known upfront: prefix sums + binary search, not reservoir sampling.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1With what probability does the i-th item replace the candidate?Reveal

    1/i.

  • 2Why is replacing with probability 1/2 every time wrong?Reveal

    The last item ends at 1/2 and the first at (1/2)^(n−1). The chance must shrink as more items are seen.

  • 3With a reservoir of k, what happens to item i > k?Reveal

    It gets in with probability k/i and replaces a uniformly random slot.

Practice ladder

every problem →
  1. 1Linked List Random Nodethe hookMedium
  2. 2Random Pick Indexonly matches countMedium
  3. 3Shuffle an Arraya whole random orderMedium
  4. 4Random Pick with Weightweights: not a reservoirMedium
  5. 5Insert Delete GetRandom O(1)a changing setMedium
  6. 6Love-Haterandom picks that are probably good2400

Finished Reservoir Sampling? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Reservoir Sampling

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial