Sub topic 2
Proving Every Permutation Is Equally Likely
This chapter assumes you have read the in-place Fisher-Yates code from the previous chapter. It also assumes you know that a fair shuffle gives each of the n! orderings probability 1/n!.
The Counting Proof
The loop runs i from n−1 down to 1. At each step, j is chosen uniformly from the i+1 positions 0 through i. The choices are independent, so the number of equally likely choice sequences is:
(n) · (n−1) · … · 2 = n!
Each sequence therefore has probability 1/n!. Two different sequences always produce different permutations. The first choice fixes which item ends up in the last position, and nothing touches that position again. The second choice fixes the next position, and so on. Sequences and permutations therefore match one to one, so every permutation has probability exactly 1/n!.
Cost: O(n) Time, O(1) Extra Space
The loop does n−1 iterations. Each iteration makes one random draw and one swap, so the running time is O(n). The shuffle happens inside the input list and uses only a few index variables, so it needs O(1) extra space.
Off-by-One Errors That Break Fairness
The proof depends on each range being exactly 0..i. Small slips in the bounds change the count of outcomes:
| Index choice | Outcomes | Result |
|---|---|---|
| `randint(0, i)` | n! | Fair |
| `randrange(i)` (0..i−1) | (n−1)! | Sattolo's algorithm: no item ever stays in its original position |
| `randint(0, n - 1)` | nⁿ | Naive shuffle, biased |
| loop stops at `i > 1` | n!/2 | Never performs the last swap, so it reaches only half the orderings |
Drawing Unbiased Random Indices
Even with the correct range, x % n on a raw 32-bit value is biased when n does not divide 2³². The smaller remainders come up slightly more often. The fix is rejection sampling: throw away any value at or above the largest multiple of n that fits, then draw again.
import secrets
def random_below(n):
limit = (2**32 // n) * n
while True:
x = secrets.randbits(32)
if x < limit:
return x % n
print(random_below(6))Each draw is rejected with probability less than 1/2, so the expected number of draws stays below 2.
Exercise
For n = 4, how many outcomes does the correct shuffle have, and how many does the version using randrange(i) have? Which permutation of [0, 1, 2, 3] can the randrange(i) version never produce?
Show answer
The correct shuffle has 4! = 24 outcomes. The randrange(i) version has 3! = 6, all of them single cycles. It can never return the identity [0, 1, 2, 3], or any ordering that leaves an element in its original position.