Fisher-Yates Uniformity Proof and Pitfalls
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Examine the in-place left-to-right Fisher-Yates (Knuth) shuffle over a list arr containing n distinct items:
import random
def shuffle(arr: list[int]) -> None:
n = len(arr)
for i in range(n - 1):
j = random.randint(i, n - 1)
arr[i], arr[j] = arr[j], arr[i]
Assuming random.randint(a, b) draws an integer uniformly and independently from {a, a + 1, ..., b}, work through the following three questions:
- Inductive correctness proof: State a formal loop invariant describing the distribution of the locked prefix
arr[0 : i], and prove by induction acrossi = 0, 1, ..., n - 2that right after iterationi,arr[0 : i + 1]is an equally likely ordering ofi + 1distinct items from the input, and that once the loop finishes, alln!permutations ofarrhave exact probability1 / n!. - Full-range swap bug: Suppose a developer mistakenly writes
j = random.randint(0, n - 1)inside the loop so every step draws from the entire array. Give a counting/divisibility proof (illustrated on a small input such asn = 3) showing why the output distribution cannot be uniform. - Remainder skew (
rand() % k): Supposerandint(i, n - 1)is built on top of a C-style generatorrand()uniform on{0, 1, ..., RAND_MAX}viai + (rand() % (n - i)). Derive the exact selection probabilities whenRAND_MAX + 1is not a multiple ofn - i, and specify which indices are over-represented and by how much.
Scope & Expectations
- Ordered-prefix invariant: Track ordered
k-tuples (k-permutations) inarr[0 : k]rather than unordered subsets alone, handling both the base case and conditional probability in the inductive step rigorously. - Clean counting disproof: Relate the total number of equally likely random-choice trajectories under
[0, n - 1]ton!and show explicitly why equal probabilities are impossible forn >= 3. - Exact remainder math: Express
RAND_MAX + 1 = q * (n - i) + rvia quotient and remainder, derive the exact probabilities for favored versus unfavored indices, and state when the skew vanishes.
Step-by-step walkthrough
Understand how the forward shuffle locks in one slot per step
Imagine drawing names out of a hat, except the hat and the output list share the same array
arrofndistinct elementsx_0, x_1, ..., x_{n-1}:- Everything before index
i(arr[0 : i]) has already been drawn and locked in place. - Everything from index
ito the end (arr[i : n]) is still in the hat, waiting to be chosen.
At step
i(fori = 0, 1, ..., n - 2), the algorithm picks a random indexjuniformly from{i, i + 1, ..., n - 1}(independently of all earlier picks) and swapsarr[i]witharr[j]:Start: [ X Y Z ] locked prefix = [] hat = indices 0..2 (3 items) i = 0: pick j in {0,1,2}, say j = 2 -> swap arr[0] and arr[2] [ Z | Y X ] locked prefix = [Z] hat = indices 1..2 (2 items) i = 1: pick j in {1,2}, say j = 1 -> swap arr[1] and arr[1] [ Z Y | X ] locked prefix = [Z, Y] hat = index 2 (1 item left) End: [ Z, Y, X ] only 1 item remains, so index 2 is automatically fixedTo track ordered prefixes cleanly, define one term:
- An ordered arrangement of length
k(also called ak-permutation) is an ordered tuple(a_0, a_1, ..., a_{k-1})ofkdistinct elements from the original array. There aren * (n - 1) * ... * (n - k + 1) = n! / (n - k)!such arrangements in total. For example, withn = 3elements{X, Y, Z}andk = 2, there are3! / 1! = 6ordered arrangements:(X, Y), (X, Z), (Y, X), (Y, Z), (Z, X), (Z, Y).
If
n <= 1,range(n - 1)is empty, the loop performs zero iterations, and the sole permutation has probability1 = 1 / n!(since0! = 1and1! = 1). From here on, assumen >= 2and assume in Parts 1–2 thatrandom.randintis perfectly uniform.- Everything before index
Part 1a: State the exact loop invariant
A loop invariant is a precise claim about the array's state that holds before the first iteration and stays true after every iteration. To reach a statement about full ordered permutations at the end, our invariant must state the probability of each ordered prefix — merely saying "every subset of size
kis equally likely" ignores whether thek!orderings inside the prefix are equally likely.State invariant
I(k)afterkelements have been locked intoarr[0 : k](sok = 0holds before stepi = 0, andk = i + 1holds right after stepi):Invariant I(k), for 0 <= k <= n - 1: (a) For EVERY ordered arrangement (a_0, a_1, ..., a_{k-1}) of k distinct elements from the original array: P(arr[0 : k] == [a_0, a_1, ..., a_{k-1}]) = (n - k)! / n! (b) The suffix arr[k : n] contains the remaining n - k original elements in some order.Part
(b)always holds because swapping two array slots never creates, deletes, or duplicates elements.Why does
(a)directly prove that right after iterationi,arr[0 : i + 1]is an equally likely ordering of a uniformly chosen(i + 1)-element subset? Setk = i + 1and fix any subsetSofkoriginal elements:Scan be ordered ink!ways, and by(a)each ordering has probability(n - k)! / n!.- Summing over all
k!orderings givesP(set(arr[0 : k]) == S) = k! * (n - k)! / n! = 1 / C(n, k), so the subsetSitself is chosen uniformly at random. - Conditioning on
set(arr[0 : k]) == S, every ordering ofShas probability((n - k)! / n!) / (k! * (n - k)! / n!) = 1 / k!, which is a uniformly random permutation ofS.
Base case (
k = 0, beforei = 0, andk = 1, afteri = 0):- At
k = 0,arr[0 : 0]is the empty prefix[]. There isn! / n! = 1empty arrangement, andP(arr[0 : 0] == []) = 1 = (n - 0)! / n!. Allnoriginal elements sit inarr[0 : n]. - Sanity check after step
i = 0(k = 1): for any elementa_0initially at indexp,arr[0] == a_0after step0happens if and only ifj = p, which has probability1 / n = (n - 1)! / n!, matchingI(1).
Part 1b: Prove the inductive step
Assume
I(i)holds right before stepifor some0 <= i <= n - 2. We must proveI(i + 1)holds right after stepi.Fix any ordered arrangement
(a_0, a_1, ..., a_{i-1}, a_i)ofi + 1distinct original elements. Stepipicksjin{i, ..., n - 1}and swapsarr[i]witharr[j]. Because bothi >= iandj >= i, stepinever modifiesarr[0 : i]. Therefore, the new prefixarr[0 : i + 1]equals[a_0, ..., a_{i-1}, a_i]after stepiif and only if two events both happen:Event A: Before step i, arr[0 : i] == [a_0, ..., a_{i-1}] Event B: During step i, element a_i is swapped into index iBy the induction hypothesis
I(i)(a), we already knowP(A) = (n - i)! / n!.Now find
P(B | A):- Whenever Event A holds,
a_iis distinct froma_0, ..., a_{i-1}, soa_iis not inarr[0 : i]. - By
I(i)(b),a_isits at exactly one indexpinside{i, i + 1, ..., n - 1}right before stepi. - Step
iplacesa_iintoarr[i]if and only if the random drawjequals that exact indexp. - Because
jis drawn uniformly from then - iindices{i, i + 1, ..., n - 1}and is completely independent of all earlier draws (which determined Event A andp),P(j == p | A) = 1 / (n - i).
Multiply
P(A)andP(B | A)using the chain rule of probability:P(arr[0 : i + 1] == [a_0, ..., a_i]) = P(A) * P(B | A) = ((n - i)! / n!) * (1 / (n - i)) = (n - i - 1)! / n! = (n - (i + 1))! / n!After the swap,
arr[i + 1 : n]holds the remainingn - (i + 1)elements not in[a_0, ..., a_i]. ThusI(i + 1)holds, completing the induction.Notice why we never needed
arr[i : n]itself to be uniformly shuffled! (In fact, for[X, Y, Z], if step0picksj = 0soarr[0] = X, the suffix is deterministically[Y, Z], never[Z, Y].) That poses zero problem becausejchooses uniformly among indices{i, ..., n - 1}, giving whichever single slot holdsa_ithe exact chance1 / (n - i).- Whenever Event A holds,
Part 1c: Conclude uniformity of all n! permutations and cross-check
The loop runs for
i = 0, 1, ..., n - 2. Right after the final iterationi = n - 2, invariantI(n - 1)holds:- For any full permutation
(a_0, a_1, ..., a_{n-2}, a_{n-1}), part(a)ofI(n - 1)saysarr[0 : n - 1] == [a_0, ..., a_{n-2}]has probability(n - (n - 1))! / n! = 1! / n! = 1 / n!. - Whenever the first
n - 1positions holda_0, ..., a_{n-2}, part(b)guarantees the single remaining elementa_{n-1}is forced into the final slotarr[n - 1].
Therefore, every one of the
n!permutations ofarris produced with probability:P(arr == [a_0, a_1, ..., a_{n-1}]) = 1 / n!This also shows why stopping at
i = n - 2is exact: an extra stepi = n - 1would only drawjfrom{n - 1}and swaparr[n - 1]with itself.Counting cross-check: Across steps
0, 1, ..., n - 2, the number of possible draw sequences(j_0, j_1, ..., j_{n-2})isn * (n - 1) * ... * 2 = n!, each occurring with probability1 / n!. Because every permutation is reachable with probability1 / n!, thosen!draw sequences map one-to-one (a bijection) onto then!permutations. We can verify this exhaustively in Python forn = 4:from itertools import product def count_forward_shuffle_outcomes(n: int) -> dict: """Run every possible (j_0, ..., j_{n-2}) sequence and count final permutations.""" counts = {} choice_ranges = [range(i, n) for i in range(n - 1)] for draws in product(*choice_ranges): arr = list(range(n)) for i, j in enumerate(draws): arr[i], arr[j] = arr[j], arr[i] perm = tuple(arr) counts[perm] = counts.get(perm, 0) + 1 return counts outcomes = count_forward_shuffle_outcomes(4) print(len(outcomes), set(outcomes.values())) # 24 {1} -> all 24 permutations appear once- For any full permutation
Part 2: Why picking j from [0, n - 1] breaks uniformity
Now consider replacing
randint(i, n - 1)with the buggyj = random.randint(0, n - 1). Intuitively, later steps can reach back intoarr[0 : i]and evict elements that were already placed, breaking the "prefix is frozen" property that made the induction work.A simple divisibility argument proves uniformity is impossible:
- In each of the
n - 1iterations,jis chosen uniformly fromnindices (0throughn - 1), producingn^(n - 1)equally likely draw sequences(j_0, ..., j_{n-2}), each with probability1 / n^(n - 1). - Every permutation's probability is
c / n^(n - 1), wherecis the integer number of draw sequences producing that permutation. - For every one of the
n!permutations to have probability1 / n!, each would needc = n^(n - 1) / n!draw sequences — which requiresn!to dividen^(n - 1)evenly!
Worked trace for
n = 3(arr = [X, Y, Z]): There are3^2 = 9equally likely draw pairs(j_0, j_1)but3! = 6permutations. Since9 / 6 = 1.5is not an integer, the 9 paths cannot split evenly across 6 permutations:Start [X, Y, Z]: j_0 = 0 -> [X, Y, Z]: j_1 = 0 -> [Y, X, Z] j_1 = 1 -> [X, Y, Z] j_1 = 2 -> [X, Z, Y] j_0 = 1 -> [Y, X, Z]: j_1 = 0 -> [X, Y, Z] j_1 = 1 -> [Y, X, Z] j_1 = 2 -> [Y, Z, X] j_0 = 2 -> [Z, Y, X]: j_1 = 0 -> [Y, Z, X] j_1 = 1 -> [Z, Y, X] j_1 = 2 -> [Z, X, Y] Totals out of 9 equally likely paths: [X, Y, Z]: 2/9 [Y, X, Z]: 2/9 [Y, Z, X]: 2/9 (twice as likely!) [X, Z, Y]: 1/9 [Z, X, Y]: 1/9 [Z, Y, X]: 1/9Even if the loop runs
ntimes (for i in range(n):),3^3 = 27is still not divisible by6(27 / 6 = 4.5), giving probabilities5/27vs4/27:from itertools import product def count_buggy_outcomes(n: int, steps: int) -> dict: """Count final permutations when j is drawn from [0, n - 1] on every step.""" counts = {} for draws in product(range(n), repeat=steps): arr = list("XYZUVW"[:n]) for i, j in enumerate(draws): arr[i], arr[j] = arr[j], arr[i] perm = "".join(arr) counts[perm] = counts.get(perm, 0) + 1 return dict(sorted(counts.items())) print(count_buggy_outcomes(3, 2)) # {'XYZ': 2, 'XZY': 1, 'YXZ': 2, 'YZX': 2, 'ZXY': 1, 'ZYX': 1} print(count_buggy_outcomes(3, 3)) # {'XYZ': 4, 'XZY': 5, 'YXZ': 5, 'YZX': 5, 'ZXY': 4, 'ZYX': 4}Why this fails for every
n >= 3(and any number of stepsm): Forn >= 3, the integern - 1 >= 2has at least one prime factorp. Becausenandn - 1differ by1, dividingnbypleaves remainder1, sopdoes not dividen— and thereforepcannot divide any powern^m. Yetpdividesn - 1, which dividesn! = n * (n - 1) * ... * 1. Hencen!never dividesn^(n - 1)orn^nfor anyn >= 3. (Onlyn = 2escapes because2^1 = 2! = 2.)- In each of the
Part 3a: Derive the modulo-bias formula for rand() % (n - i)
Suppose
rand()returns an integer uniformly from{0, 1, ..., RAND_MAX}, givingM = RAND_MAX + 1equally likely raw values, and we computej = i + (rand() % k)wherek = n - iis the number of remaining slots in[i, n - 1].Divide
Mbykusing integer division with remainder:M = q * k + r, where q = M // k and 0 <= r < kAs
vsteps through0, 1, ..., M - 1, its remaindert = v % kcycles repeatedly through0, 1, ..., k - 1:- The first
q * kraw values (0throughq * k - 1) formqcomplete cycles of lengthk, hitting every offsett in {0, ..., k - 1}exactlyqtimes. - When
r > 0, the remainingrleftover raw values (q * k, q * k + 1, ..., q * k + r - 1) wrap around to offsets0, 1, ..., r - 1, giving each of those firstroffsets one extra hit!
Here is a miniature picture with
RAND_MAX = 7(M = 8) andk = 3, where8 = 2 * 3 + 2(q = 2, r = 2):rand() value v : 0 1 2 | 3 4 5 | 6 7 offset t = v%3 : 0 1 2 | 0 1 2 | 0 1 \_______/ \_______/ \___/ cycle 1 cycle 2 r = 2 leftovers! Outcome counts out of M = 8: t = 0 (index i + 0): 3 / 8 = (q + 1) / M <- favored t = 1 (index i + 1): 3 / 8 = (q + 1) / M <- favored t = 2 (index i + 2): 2 / 8 = q / M <- under-pickedIn general, for every offset
t in {0, 1, ..., k - 1}(corresponding to chosen indexj = i + t):P(j = i + t) = (q + 1) / M for 0 <= t < r (first r indices [i .. i + r - 1] get higher probability) P(j = i + t) = q / M for r <= t < k (last k - r indices [i + r .. n - 1] get lower probability)Notice that
r * ((q + 1) / M) + (k - r) * (q / M) = (q * k + r) / M = M / M = 1. The bias disappears if and only ifr == 0, meaningn - ievenly dividesRAND_MAX + 1.- The first
Part 3b: Quantify how modulo bias skews real shuffles
Each favored index (
ithroughi + r - 1) has probability(q + 1) / Mversusq / Mfor unfavored indices (i + rthroughn - 1) — an absolute gap of1 / Mand a relative ratio of(q + 1) / q. How severe that ratio is depends onk = n - irelative toM = RAND_MAX + 1:def modulo_counts(m: int, k: int) -> list: """Count how many of the m raw rand() values land on each remainder 0..k-1.""" counts = [0] * k for raw_val in range(m): counts[raw_val % k] += 1 return counts print(modulo_counts(8, 3)) # [3, 3, 2] -> 3/8 vs 2/8 (1.5x ratio) c_small = modulo_counts(32768, 3) print(c_small) # [10923, 10923, 10922] -> tiny ~0.009% skew c_large = modulo_counts(32768, 20000) print(c_large[0], c_large[19999]) # 2 vs 1 -> early indices are 2x as likely!- Small
k, largeM(mild but systematic): The C standard only guaranteesRAND_MAX >= 32767(M = 32768 = 2^15). Fork = 3,q = 10922andr = 2, so offsets0and1have probability10923 / 32768(0.333344) while offset2has10922 / 32768(0.333313). WhenMis a power of two, every step whosen - iis not a power of two suffers bias. kcomparable toM(severe): WithM = 32768andk = 20000,q = 1andr = 12768. Ati = 0, each of the first12,768elements lands at index0with probability2 / 32768— twice as often as each of the last7,232elements (1 / 32768).k > M(catastrophic): Nowq = 0andr = M. Offsets0 .. M - 1get1 / Meach, while offsetsM .. k - 1get0 / M = 0and can never be selected for indexi!
In our Part 1 proof, modulo bias breaks
P(B | A) = 1 / (n - i). Because draw sequences(j_0, ..., j_{n-2})still map one-to-one onto then!permutations, each permutation's probability is the product of itsn - 1step probabilities — so permutations produced by smaller offsets (t < r, including leaving elements near their starting positions) become systematically more probable than permutations requiring larger offsets (t >= r).- Small
Intuition & how it works
Think of the forward Fisher-Yates (Knuth) shuffle as drawing slips of paper out of a shrinking hat, right inside the array. Imagine a sliding divider starting at index 0: everything to the left of the divider (arr[0 : i]) has already been dealt onto the table and is frozen forever, while everything from the divider to the end (arr[i : n]) is still inside the hat. At step i, picking j uniformly from [i, n - 1] and swapping arr[i] with arr[j] reaches blindly into the hat, places one random remaining item onto slot i, and moves the divider one position right.
Naive variations break this clean "dealt vs. still in the hat" boundary or distort the draw itself. If you pick j from the whole array [0, n - 1] on every step, later swaps reach back onto the table and scramble already-dealt cards, creating n^(n - 1) equally likely execution paths — a number that can never divide evenly among n! permutations once n >= 3. And if you shrink a raw random integer using rand() % (n - i), leftover numbers near RAND_MAX wrap around to 0, 1, ... and make smaller offsets slightly (or up to 2x) more likely than larger ones.
Watch how the clean probabilities multiply on a tiny 3-element array [X, Y, Z] (n = 3, 3! = 6 permutations):
- Step
i = 0(hat = indices0, 1, 2):jis uniform over3slots, soX,Y, orZlands atarr[0]with probability1/3each. Index0is never touched again. - Step
i = 1(hat = indices1, 2): SupposeZlanded atarr[0], leavingYandXat indices1and2. Nowjis uniform over{1, 2}, soYorXlands atarr[1]with probability1/2each, and whichever wasn't picked is forced intoarr[2]. - Result: Every specific final ordering — such as
[Z, Y, X]— occurs with probability(1/3) * (1/2) * 1 = 1/6 = 1/3!.
Key points
- Ordered-prefix loop invariant: A loop invariant (a property true before the loop and preserved by every step) must track ordered prefixes, not just unordered sets. After
ksteps (k = i + 1), every ordered arrangement (k-permutation, an ordered sequence ofkdistinct original elements) appears inarr[0 : k]with probability(n - k)! / n!, whilearr[k : n]holds the remainingn - kelements. - Why the inductive step works: Step
ionly swaps indices>= i, soarr[0 : i]stays frozen (P(A) = (n - i)! / n!). Given that prefix, the next target elementa_isits at exactly one slotpin{i, ..., n - 1}, and an independent uniform drawjover{i, ..., n - 1}hitspwith probability1 / (n - i), giving((n - i)! / n!) * (1 / (n - i)) = (n - i - 1)! / n!. - Termination and bijection: After
i = n - 2, every(n - 1)-element prefix has probability1! / n! = 1 / n!, and the single leftover element is forced intoarr[n - 1]. Equivalently, then * (n - 1) * ... * 2 = n!draw sequences map via a bijection (an exact one-to-one pairing) onto then!permutations. - Range bug (
jin[0, n - 1]): Producesn^(n - 1)equally likely paths. Forn >= 3,n - 1andnare coprime (they share no prime factor>= 2), so any prime dividingn - 1dividesn!but never dividesn^(n - 1)— making1 / n!impossible (2/9vs1/9forn = 3). - Modulo bias (
rand() % k): Modulo bias is the uneven remainder distribution caused when the generator's range sizeM = RAND_MAX + 1is not a multiple ofk = n - i. WritingM = q * k + r(0 <= r < k), indicesi .. i + r - 1get probability(q + 1) / Mwhile indicesi + r .. n - 1getq / M.
Common mistakes
- Stating an unordered-subset invariant: Proving only that
set(arr[0 : i + 1])is a uniformly chosen subset of sizei + 1(1 / C(n, i + 1)) leaves open whether one ordering of that subset happens more often than another, so ati = n - 2it cannot distinguish the(n - 1)!permutations of the prefix. - Assuming the suffix
arr[i : n]is uniformly shuffled: It is not, and the proof never assumes it. Starting from[X, Y, Z], if step0picksj = 0(arr[0] = X), the suffix is100%[Y, Z]and0%[Z, Y]— yet step1still picksYorZwith probability1/2each. - Proving only marginal
1/nslot probabilities: Showing "every element lands at every index with probability1/n" does not prove alln!permutations are equally likely. A random cyclic shift puts every element at every index with probability1/n, yet produces onlynof then!permutations! - Off-by-one
randint(i + 1, n - 1)(Sattolo's algorithm): Excludingiforces every element out of its current slot, producing only single-cycle permutations ((n - 1)!of them; for[X, Y, Z], only[Y, Z, X]and[Z, X, Y], never[X, Y, Z]). - Confusing inclusive and exclusive endpoints: Python's
random.randint(i, n - 1)includesn - 1, whereasrandom.randrange(i, n - 1)excludesn - 1and silently leaves the last element stranded wheni = n - 2. - Replacing
% kwith floating-point scalingint(rand() / (RAND_MAX + 1.0) * k): Any deterministic function mappingMequally likely integers ontokbuckets assigns every bucket an integer multiple of1 / M, so ifkdoes not divideM, floating-point scaling still has the exact same(q + 1) / Mvsq / Mbias — just spread across spaced-out buckets instead of bunched at0 .. r - 1.
Follow-up questions
- Given
rand()uniform on[0, RAND_MAX], how can you use rejection sampling to draw a bias-free integer in[0, k - 1]? Rejection sampling discards out-of-range draws and retries so the kept draws divide evenly across allkoutcomes. SetM = RAND_MAX + 1and letlimit = M - (M % k) = q * kbe the largest multiple ofkless than or equal toM; loop callingv = rand()untilv < limit, then returnv % k. Because{0, 1, ..., limit - 1}contains exactlyqfull cycles of0 .. k - 1(assuming1 <= k <= M), every outcome has exact conditional probabilityq / limit = 1 / k, and sincelimit > M / 2, each draw succeeds with probability> 1/2(< 2expected calls torand()). Ifk > M, first combine multiplerand()calls in baseMto build a uniform range larger thank, then apply the same threshold rejection.
python
def uniform_int(k: int, rand_fn, rand_max: int) -> int:
"""Return a strictly uniform integer in [0, k - 1] (requires 1 <= k <= rand_max + 1)."""
m = rand_max + 1
limit = m - (m % k) # largest multiple of k <= m; values >= limit cause bias
while True:
raw = rand_fn()
if raw < limit:
return raw % k
-
Even with a bug-free Fisher-Yates implementation, can a generator with 32 bits of state reach all permutations of a 52-card deck? No, if the pseudo-random number generator (PRNG, a deterministic state machine producing random-looking numbers) has only 32 bits of internal state — or is seeded with a 32-bit seed — it has at most
2^32(about4.29 * 10^9) possible starting states, so the deterministic shuffle can output at most2^32distinct decks. A 52-card deck has52!, roughly8.07 * 10^67(about2^225.6) permutations, meaning a 32-bit state or seed can reach less than10^-58of all possible deals! Reaching every permutation requires at leastceil(log2(52!)) = 226bits of internal state and at least226bits of seed entropy (note that Python's Mersenne Twister has19,937bits of state, which is plenty, provided you seed it from OS entropy rather than a 32-bit integer). -
How would you modify the inductive argument when items arrive one by one from a stream of unknown length, as in reservoir sampling? When
nis unknown upfront, move the invariant from "prefix of a fixed array" to "allmstream items seen so far" so uniformity holds after every arrival. For a full streaming shuffle (the inside-out Fisher-Yates algorithm), when itemm - 1(them-th element,m >= 1) arrives, append it at indexm - 1, pickjuniformly from[0, m - 1], and swaparr[m - 1]witharr[j]: by induction, any target permutation ofmitems places the newest item at some slotj*(1 / mchance) and came from a unique(m - 1)-item permutation (1 / (m - 1)!chance), giving1 / m!. When you only have memory for a sample of sizes(Reservoir Sampling, Algorithm R), keep the firstsitems, and for them-th item (0-based indexm - 1 >= s) drawjuniformly from[0, m - 1]and overwritereservoir[j]ifj < s: by induction onm, everys-element subset of themitems seen so far sits in the reservoir with equal probability1 / C(m, s)(survival of an olds-subset is(1 / C(m - 1, s)) * ((m - s) / m) = 1 / C(m, s), and forming a news-subset containing itemm - 1sums(m - s)single-slot replacements of probability(1 / C(m - 1, s)) * (1 / m)to1 / C(m, s)).
Follow-up questions
- Given `rand()` uniform on `[0, RAND_MAX]`, how can you use rejection sampling to draw a bias-free integer in `[0, k - 1]`?
- Even with a bug-free Fisher-Yates implementation, can a generator with 32 bits of state reach all permutations of a 52-card deck?
- How would you modify the inductive argument when items arrive one by one from a stream of unknown length, as in reservoir sampling?
Similar questions
- Audit and Harden Production Shell Snippets
- Linear-Time In-Place Digit Sort
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging