Unit 6 of 6 · about 4 hours · implement, measure
Reservoir sampling, unbiased shuffling and empirical checks
Streams do not fit in memory and shuffles must be uniform, not merely random-looking. The proof is one induction; the check is a seeded experiment you can rerun.
You'll be able to
- Implement reservoir sampling and prove each position is kept with the claimed probability by induction.
- Implement Fisher-Yates and show every permutation is equally likely by counting paths.
- Test a sampler empirically with fixed seeds, trial counts, and tolerances, using pytest and Hypothesis for property and uniformity checks.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Randomized algorithms: Fisher-Yates, reservoir, rejectionDSA Handbook - recursion, backtracking and greedy
Fisher-Yates shuffle in linear time; Reservoir sampling with the equal-probability induction; Pitfalls: naive swap, Sattolo cycles, modulo bias, 32-bit PRNG limits
- Discrete Probability: shufflesAlgorithms lecture notes - randomized algorithms
1.6 Random Permutations (DrawLots, FisherYates, SelectionShuffle and InsertionShuffle); Exercise 10(a), NaiveShuffle on
Exercise 11, QuickShuffle, is optional depth.
- Nuts and Bolts, Exercise 4: stream samplingAlgorithms lecture notes - randomized algorithms
Exercise 4(a) and 4(b): one and uniform samples from a stream in and space without knowing its length
- Sampling estimationMIT 6.042J - probability and randomized algorithms
Session 34: Chapter 19.4 Estimation by Random Sampling and 19.5 Confidence versus Probability
Focus on
- Reservoir induction: with one slot, the old item survives with probability , so each of the first items is kept with .
- Fisher-Yates has exactly equally likely paths. CPython
random.Random.shuffleon 3.13.14 loops backwards with_randbelow, checked withinspectagainst the installed source. - Naive swap-with-any-index has paths over permutations and is biased; the rand-below-i variant (Sattolo) yields only single cycles; a 32-bit seed cannot reach all orders.
- Empirical contract: sizes, seed, trials, tolerance.
random.Random(0).shuffleon 4 items, 4800 times, gives counts from 172 to 220 against 200 expected and a chi-square statistic of 22.6, under the 0.001 critical value of 49.7 at 23 degrees of freedom. The naive swap-with-any-index shuffle scores 126.7.
Common mistakes · 3
- An off-by-one in the replacement range silently biases late items. The seeded fraction-kept check against catches it; eyeballing a few samples does not.
- Shuffling with a random comparator, or by sorting on random keys from a small range. A random comparator is inconsistent, so the result depends on the sort algorithm; tied keys keep input order under a stable sort. Distinct random float keys are uniform but cost ; Fisher-Yates is .
- Unseeded empirical tests that flake. Seed every RNG, record trials and tolerance, and rerun the exact command before claiming uniformity.
Try it yourself
Closed-book, before checking anything
i >= k draw j = rng.randrange(i + 1) and replace slot j when j < k). With over range(100) and random.Random(0) it returns [63, 1, 2, 50, 34]. Over seeds 0 to 3999 on range(50), item 0 is kept with fraction 0.0985 against theory 0.1. Write a pytest file with a Hypothesis permutation-preservation property for your Fisher-Yates and the seeded chi-square check above; expect 2 passed.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Prove the reservoir induction step for one slot.Answer
Assume each of the first items is kept with . Item is kept with , and each old item survives with , giving .
2.Why is swapping each position with any of indices biased for ?Answer
It has paths over 6 permutations, and 27 is not divisible by 6, so some permutations must get more paths than others.
3.What does the Sattolo variant generate?Answer
Only single -cycles: each position swaps with a strictly earlier index, so fixed points and short cycles never appear.
4.Your shuffle gives a chi-square of 22.6 over 24 permutations from 4800 trials. What does that show?Answer
The counts are consistent with uniform: 23 degrees of freedom expect a statistic near 23, and the 0.001 critical value is 49.7. It does not prove uniformity; it fails to detect bias at this sample size, while the naive shuffle's 126.7 is detected.
Practice
- LeetCode 382: Linked List Random Node
Calls
SolutionthengetRandomrepeatedly on[1, 2, 3]. Implement with reservoir sampling at in extra space.After submitting, reread the DSA Handbook reservoir section and check your replacement probability against its induction.
- LeetCode 384: Shuffle an Array
Calls
Solution,shuffle,reset,shuffleon[1, 2, 3]. Implement Fisher-Yates and test uniformity over fixed seeds.After submitting, compare with the DSA Handbook Fisher-Yates section and its naive-shuffle counterexample.
You're done when
Both problems are accepted, and your seeded reservoir and chi-square checks reproduce the stated numbers.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 2 more in the section
- DSA Handbook - recursion, backtracking and greedyHandbook Academy · primary
Study Part 7, Part 10 and the relevant foundations on recursion and probability. Write the state definition or greedy claim before opening code.
- MIT 6.042J - probability and randomized algorithmsMIT OpenCourseWare · support
Use the probability, expectation and concentration readings to derive sampling probabilities and distinguish expected from high-probability guarantees.
- Algorithms lecture notes - randomized algorithmsJeff Erickson · support
Use note 1 Discrete Probability, note 2 Nuts and Bolts (randomized quicksort, with QuickSelect in its exercises), note 4 Tail Inequalities and note 5 Hashing to derive expected costs, separate expected from high-probability guarantees, and analyze hashing behavior.
Also in this section
- AlgoMaster DSA - decomposition and greedy sliceAlgoMaster · required
Attempt N-Queens and Gas Station cold, then implement reservoir sampling and test its output distribution over fixed-seed trials. Add another judged problem only for a diagnosed weakness.
- Algorithms - recursion, backtracking and greedyJeff Erickson · required
Use the recursion, backtracking, divide-and-conquer and greedy chapters for recurrence derivations, proof templates and counterexamples.