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

O(n) / O(1) space

Keep the current pick; for the i-th item, replace it with probability 1/i.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
0%
mastery
0/4 solved
IdeaPracticeTemplatePitfalls

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.

  1. 1Brute force

    Store everything, then sample.

  2. 2The observation

    O(n) memory: probabilities telescope so each seen item stays with probability k/n.

  3. 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

Next · Foundation

Linked List Random Node

Keep the i-th node with probability 1/i.

0/4 solved
  • 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

Variants and techniques

  • Randomised Sampling ArgumentsCP 2400+If a constant fraction p of the elements (often 1/2) belongs to some optimal answer, pick a few random elements as candidates and verify each one. The failure probability is (1 - p)^t after t trials.

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

    Love-Hate

Resources

  • Segment Treecp-algorithms · article
  • Fenwick Treecp-algorithms · article
  • ITMO Segment Tree courseCodeforces EDU · course
  • Efficient and easy segment treesAl.cash · blog
  • Meet in the MiddleUSACO Guide · course
  • Matrix ExponentiationUSACO Guide · course
  • Reservoir samplingWikipedia · article
Segment Tree / Fenwick (BIT)Meet in the Middle
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial