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

Technique · CP 2400+

Randomised Sampling Arguments

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.

Learn firstMath / Number TheoryHash Map / Hash Set Lookup
0%
mastery
0/3 solved
Practise nextGhd
IdeaPracticePitfalls

Recognise it

The signal

the answer must divide / agree with at least half of the elements

  1. 1Brute force

    Try every element as the candidate: O(n) candidates x O(n) check.

  2. 2The observation

    The number of candidates.

  3. 3Why it works

    Each trial independently hits a valid candidate with probability >= p.

Reach for it when

  • +objects defined by majority ('liked by at least half')
  • +deterministic search looks exponential, but a random element is good with probability >= 1/2

Not when

  • ×anti-hash style tests against a fixed seed (seed from a high-resolution clock)
  • ×no fraction guarantee exists

Practice

Next

Ghd

0/3 solved
  • GhdCodeforces2900
  • Love-HateCodeforces2400
  • Kuroni and the PunishmentCodeforces2500

Pitfalls

Misconceptions

  • !using rand() with a small RAND_MAX
Go deeper1 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

    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
TodayReviewPatternsProblems