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:

  1. Inductive correctness proof: State a formal loop invariant describing the distribution of the locked prefix arr[0 : i], and prove by induction across i = 0, 1, ..., n - 2 that right after iteration i, arr[0 : i + 1] is an equally likely ordering of i + 1 distinct items from the input, and that once the loop finishes, all n! permutations of arr have exact probability 1 / n!.
  2. 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 as n = 3) showing why the output distribution cannot be uniform.
  3. Remainder skew (rand() % k): Suppose randint(i, n - 1) is built on top of a C-style generator rand() uniform on {0, 1, ..., RAND_MAX} via i + (rand() % (n - i)). Derive the exact selection probabilities when RAND_MAX + 1 is not a multiple of n - i, and specify which indices are over-represented and by how much.

Scope & Expectations

  • Ordered-prefix invariant: Track ordered k-tuples (k-permutations) in arr[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] to n! and show explicitly why equal probabilities are impossible for n >= 3.
  • Exact remainder math: Express RAND_MAX + 1 = q * (n - i) + r via quotient and remainder, derive the exact probabilities for favored versus unfavored indices, and state when the skew vanishes.

Step-by-step walkthrough

  1. 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 arr of n distinct elements x_0, x_1, ..., x_{n-1}:

    • Everything before index i (arr[0 : i]) has already been drawn and locked in place.
    • Everything from index i to the end (arr[i : n]) is still in the hat, waiting to be chosen.

    At step i (for i = 0, 1, ..., n - 2), the algorithm picks a random index j uniformly from {i, i + 1, ..., n - 1} (independently of all earlier picks) and swaps arr[i] with arr[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 fixed
    

    To track ordered prefixes cleanly, define one term:

    • An ordered arrangement of length k (also called a k-permutation) is an ordered tuple (a_0, a_1, ..., a_{k-1}) of k distinct elements from the original array. There are n * (n - 1) * ... * (n - k + 1) = n! / (n - k)! such arrangements in total. For example, with n = 3 elements {X, Y, Z} and k = 2, there are 3! / 1! = 6 ordered 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 probability 1 = 1 / n! (since 0! = 1 and 1! = 1). From here on, assume n >= 2 and assume in Parts 1–2 that random.randint is perfectly uniform.

  2. 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 k is equally likely" ignores whether the k! orderings inside the prefix are equally likely.

    State invariant I(k) after k elements have been locked into arr[0 : k] (so k = 0 holds before step i = 0, and k = i + 1 holds right after step i):

    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 iteration i, arr[0 : i + 1] is an equally likely ordering of a uniformly chosen (i + 1)-element subset? Set k = i + 1 and fix any subset S of k original elements:

    • S can be ordered in k! ways, and by (a) each ordering has probability (n - k)! / n!.
    • Summing over all k! orderings gives P(set(arr[0 : k]) == S) = k! * (n - k)! / n! = 1 / C(n, k), so the subset S itself is chosen uniformly at random.
    • Conditioning on set(arr[0 : k]) == S, every ordering of S has probability ((n - k)! / n!) / (k! * (n - k)! / n!) = 1 / k!, which is a uniformly random permutation of S.

    Base case (k = 0, before i = 0, and k = 1, after i = 0):

    • At k = 0, arr[0 : 0] is the empty prefix []. There is n! / n! = 1 empty arrangement, and P(arr[0 : 0] == []) = 1 = (n - 0)! / n!. All n original elements sit in arr[0 : n].
    • Sanity check after step i = 0 (k = 1): for any element a_0 initially at index p, arr[0] == a_0 after step 0 happens if and only if j = p, which has probability 1 / n = (n - 1)! / n!, matching I(1).
  3. Part 1b: Prove the inductive step

    Assume I(i) holds right before step i for some 0 <= i <= n - 2. We must prove I(i + 1) holds right after step i.

    Fix any ordered arrangement (a_0, a_1, ..., a_{i-1}, a_i) of i + 1 distinct original elements. Step i picks j in {i, ..., n - 1} and swaps arr[i] with arr[j]. Because both i >= i and j >= i, step i never modifies arr[0 : i]. Therefore, the new prefix arr[0 : i + 1] equals [a_0, ..., a_{i-1}, a_i] after step i if 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 i
    

    By the induction hypothesis I(i)(a), we already know P(A) = (n - i)! / n!.

    Now find P(B | A):

    1. Whenever Event A holds, a_i is distinct from a_0, ..., a_{i-1}, so a_i is not in arr[0 : i].
    2. By I(i)(b), a_i sits at exactly one index p inside {i, i + 1, ..., n - 1} right before step i.
    3. Step i places a_i into arr[i] if and only if the random draw j equals that exact index p.
    4. Because j is drawn uniformly from the n - i indices {i, i + 1, ..., n - 1} and is completely independent of all earlier draws (which determined Event A and p), P(j == p | A) = 1 / (n - i).

    Multiply P(A) and P(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 remaining n - (i + 1) elements not in [a_0, ..., a_i]. Thus I(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 step 0 picks j = 0 so arr[0] = X, the suffix is deterministically [Y, Z], never [Z, Y].) That poses zero problem because j chooses uniformly among indices {i, ..., n - 1}, giving whichever single slot holds a_i the exact chance 1 / (n - i).

  4. Part 1c: Conclude uniformity of all n! permutations and cross-check

    The loop runs for i = 0, 1, ..., n - 2. Right after the final iteration i = n - 2, invariant I(n - 1) holds:

    • For any full permutation (a_0, a_1, ..., a_{n-2}, a_{n-1}), part (a) of I(n - 1) says arr[0 : n - 1] == [a_0, ..., a_{n-2}] has probability (n - (n - 1))! / n! = 1! / n! = 1 / n!.
    • Whenever the first n - 1 positions hold a_0, ..., a_{n-2}, part (b) guarantees the single remaining element a_{n-1} is forced into the final slot arr[n - 1].

    Therefore, every one of the n! permutations of arr is produced with probability:

    P(arr == [a_0, a_1, ..., a_{n-1}]) = 1 / n!
    

    This also shows why stopping at i = n - 2 is exact: an extra step i = n - 1 would only draw j from {n - 1} and swap arr[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}) is n * (n - 1) * ... * 2 = n!, each occurring with probability 1 / n!. Because every permutation is reachable with probability 1 / n!, those n! draw sequences map one-to-one (a bijection) onto the n! permutations. We can verify this exhaustively in Python for n = 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
    
  5. Part 2: Why picking j from [0, n - 1] breaks uniformity

    Now consider replacing randint(i, n - 1) with the buggy j = random.randint(0, n - 1). Intuitively, later steps can reach back into arr[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:

    1. In each of the n - 1 iterations, j is chosen uniformly from n indices (0 through n - 1), producing n^(n - 1) equally likely draw sequences (j_0, ..., j_{n-2}), each with probability 1 / n^(n - 1).
    2. Every permutation's probability is c / n^(n - 1), where c is the integer number of draw sequences producing that permutation.
    3. For every one of the n! permutations to have probability 1 / n!, each would need c = n^(n - 1) / n! draw sequences — which requires n! to divide n^(n - 1) evenly!

    Worked trace for n = 3 (arr = [X, Y, Z]): There are 3^2 = 9 equally likely draw pairs (j_0, j_1) but 3! = 6 permutations. Since 9 / 6 = 1.5 is 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/9
    

    Even if the loop runs n times (for i in range(n):), 3^3 = 27 is still not divisible by 6 (27 / 6 = 4.5), giving probabilities 5/27 vs 4/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 steps m): For n >= 3, the integer n - 1 >= 2 has at least one prime factor p. Because n and n - 1 differ by 1, dividing n by p leaves remainder 1, so p does not divide n — and therefore p cannot divide any power n^m. Yet p divides n - 1, which divides n! = n * (n - 1) * ... * 1. Hence n! never divides n^(n - 1) or n^n for any n >= 3. (Only n = 2 escapes because 2^1 = 2! = 2.)

  6. Part 3a: Derive the modulo-bias formula for rand() % (n - i)

    Suppose rand() returns an integer uniformly from {0, 1, ..., RAND_MAX}, giving M = RAND_MAX + 1 equally likely raw values, and we compute j = i + (rand() % k) where k = n - i is the number of remaining slots in [i, n - 1].

    Divide M by k using integer division with remainder:

    M = q * k + r,     where q = M // k   and   0 <= r < k
    

    As v steps through 0, 1, ..., M - 1, its remainder t = v % k cycles repeatedly through 0, 1, ..., k - 1:

    • The first q * k raw values (0 through q * k - 1) form q complete cycles of length k, hitting every offset t in {0, ..., k - 1} exactly q times.
    • When r > 0, the remaining r leftover raw values (q * k, q * k + 1, ..., q * k + r - 1) wrap around to offsets 0, 1, ..., r - 1, giving each of those first r offsets one extra hit!

    Here is a miniature picture with RAND_MAX = 7 (M = 8) and k = 3, where 8 = 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-picked
    

    In general, for every offset t in {0, 1, ..., k - 1} (corresponding to chosen index j = 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 if r == 0, meaning n - i evenly divides RAND_MAX + 1.

  7. Part 3b: Quantify how modulo bias skews real shuffles

    Each favored index (i through i + r - 1) has probability (q + 1) / M versus q / M for unfavored indices (i + r through n - 1) — an absolute gap of 1 / M and a relative ratio of (q + 1) / q. How severe that ratio is depends on k = n - i relative to M = 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!
    
    1. Small k, large M (mild but systematic): The C standard only guarantees RAND_MAX >= 32767 (M = 32768 = 2^15). For k = 3, q = 10922 and r = 2, so offsets 0 and 1 have probability 10923 / 32768 (0.333344) while offset 2 has 10922 / 32768 (0.333313). When M is a power of two, every step whose n - i is not a power of two suffers bias.
    2. k comparable to M (severe): With M = 32768 and k = 20000, q = 1 and r = 12768. At i = 0, each of the first 12,768 elements lands at index 0 with probability 2 / 32768 — twice as often as each of the last 7,232 elements (1 / 32768).
    3. k > M (catastrophic): Now q = 0 and r = M. Offsets 0 .. M - 1 get 1 / M each, while offsets M .. k - 1 get 0 / M = 0 and can never be selected for index i!

    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 the n! permutations, each permutation's probability is the product of its n - 1 step 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).

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):

  1. Step i = 0 (hat = indices 0, 1, 2): j is uniform over 3 slots, so X, Y, or Z lands at arr[0] with probability 1/3 each. Index 0 is never touched again.
  2. Step i = 1 (hat = indices 1, 2): Suppose Z landed at arr[0], leaving Y and X at indices 1 and 2. Now j is uniform over {1, 2}, so Y or X lands at arr[1] with probability 1/2 each, and whichever wasn't picked is forced into arr[2].
  3. 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 k steps (k = i + 1), every ordered arrangement (k-permutation, an ordered sequence of k distinct original elements) appears in arr[0 : k] with probability (n - k)! / n!, while arr[k : n] holds the remaining n - k elements.
  • Why the inductive step works: Step i only swaps indices >= i, so arr[0 : i] stays frozen (P(A) = (n - i)! / n!). Given that prefix, the next target element a_i sits at exactly one slot p in {i, ..., n - 1}, and an independent uniform draw j over {i, ..., n - 1} hits p with probability 1 / (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 probability 1! / n! = 1 / n!, and the single leftover element is forced into arr[n - 1]. Equivalently, the n * (n - 1) * ... * 2 = n! draw sequences map via a bijection (an exact one-to-one pairing) onto the n! permutations.
  • Range bug (j in [0, n - 1]): Produces n^(n - 1) equally likely paths. For n >= 3, n - 1 and n are coprime (they share no prime factor >= 2), so any prime dividing n - 1 divides n! but never divides n^(n - 1) — making 1 / n! impossible (2/9 vs 1/9 for n = 3).
  • Modulo bias (rand() % k): Modulo bias is the uneven remainder distribution caused when the generator's range size M = RAND_MAX + 1 is not a multiple of k = n - i. Writing M = q * k + r (0 <= r < k), indices i .. i + r - 1 get probability (q + 1) / M while indices i + r .. n - 1 get q / M.

Common mistakes

  • Stating an unordered-subset invariant: Proving only that set(arr[0 : i + 1]) is a uniformly chosen subset of size i + 1 (1 / C(n, i + 1)) leaves open whether one ordering of that subset happens more often than another, so at i = n - 2 it 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 step 0 picks j = 0 (arr[0] = X), the suffix is 100% [Y, Z] and 0% [Z, Y] — yet step 1 still picks Y or Z with probability 1/2 each.
  • Proving only marginal 1/n slot probabilities: Showing "every element lands at every index with probability 1/n" does not prove all n! permutations are equally likely. A random cyclic shift puts every element at every index with probability 1/n, yet produces only n of the n! permutations!
  • Off-by-one randint(i + 1, n - 1) (Sattolo's algorithm): Excluding i forces 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) includes n - 1, whereas random.randrange(i, n - 1) excludes n - 1 and silently leaves the last element stranded when i = n - 2.
  • Replacing % k with floating-point scaling int(rand() / (RAND_MAX + 1.0) * k): Any deterministic function mapping M equally likely integers onto k buckets assigns every bucket an integer multiple of 1 / M, so if k does not divide M, floating-point scaling still has the exact same (q + 1) / M vs q / M bias — just spread across spaced-out buckets instead of bunched at 0 .. 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 all k outcomes. Set M = RAND_MAX + 1 and let limit = M - (M % k) = q * k be the largest multiple of k less than or equal to M; loop calling v = rand() until v < limit, then return v % k. Because {0, 1, ..., limit - 1} contains exactly q full cycles of 0 .. k - 1 (assuming 1 <= k <= M), every outcome has exact conditional probability q / limit = 1 / k, and since limit > M / 2, each draw succeeds with probability > 1/2 (< 2 expected calls to rand()). If k > M, first combine multiple rand() calls in base M to build a uniform range larger than k, 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 (about 4.29 * 10^9) possible starting states, so the deterministic shuffle can output at most 2^32 distinct decks. A 52-card deck has 52!, roughly 8.07 * 10^67 (about 2^225.6) permutations, meaning a 32-bit state or seed can reach less than 10^-58 of all possible deals! Reaching every permutation requires at least ceil(log2(52!)) = 226 bits of internal state and at least 226 bits of seed entropy (note that Python's Mersenne Twister has 19,937 bits 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 n is unknown upfront, move the invariant from "prefix of a fixed array" to "all m stream items seen so far" so uniformity holds after every arrival. For a full streaming shuffle (the inside-out Fisher-Yates algorithm), when item m - 1 (the m-th element, m >= 1) arrives, append it at index m - 1, pick j uniformly from [0, m - 1], and swap arr[m - 1] with arr[j]: by induction, any target permutation of m items places the newest item at some slot j* (1 / m chance) and came from a unique (m - 1)-item permutation (1 / (m - 1)! chance), giving 1 / m!. When you only have memory for a sample of size s (Reservoir Sampling, Algorithm R), keep the first s items, and for the m-th item (0-based index m - 1 >= s) draw j uniformly from [0, m - 1] and overwrite reservoir[j] if j < s: by induction on m, every s-element subset of the m items seen so far sits in the reservoir with equal probability 1 / C(m, s) (survival of an old s-subset is (1 / C(m - 1, s)) * ((m - s) / m) = 1 / C(m, s), and forming a new s-subset containing item m - 1 sums (m - s) single-slot replacements of probability (1 / C(m - 1, s)) * (1 / m) to 1 / C(m, s)).

Follow-up questions

Similar questions

More Modal interview questions

All 3 Modal questions →