Sub topic 6
Proving Every Permutation Is Equally Likely
The previous chapter built the in-place Fisher-Yates shuffle. Running it a few thousand times and seeing even counts is encouraging, but that is only evidence. This chapter proves that each of the n! orderings comes out with probability exactly 1/n!. The proof also shows which assumptions the algorithm depends on, and that tells you where it can still fail in practice.
This chapter assumes you know the Durstenfeld loop from the previous chapter, the definition of a fair shuffle as a uniform distribution over all n! permutations, and basic probability. You should be comfortable multiplying probabilities of independent events and with the idea of a one-to-one mapping between two sets.
Here is the algorithm again for reference:
import random
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i) # 0 <= j <= i
items[i], items[j] = items[j], items[i]
return itemsWhat exactly needs proving
A run of the shuffle is completely determined by its sequence of random choices j. For a list of length n, the loop runs for i = n−1, n−2, ..., 1. At step i, j takes one of i + 1 values. So the set of possible choice sequences has this size:
n × (n−1) × ... × 2 = n!
If each draw is uniform and independent of the others, every choice sequence has probability 1/n!. The claim we need is that different choice sequences always produce different permutations. If that holds, the map from choice sequences to permutations is one-to-one. Both sets have n! elements, so a one-to-one map between them is a bijection, and each permutation inherits probability 1/n! from the one sequence that produces it.
This is the same counting argument that showed the naive shuffle is biased, run in the other direction. The naive shuffle has n^n equally likely sequences, and n^n is generally not a multiple of n!, so the sequences cannot be shared out evenly. Fisher-Yates has exactly n! sequences and no collisions.
A worked example with n = 3
Start with [A, B, C]. At step i = 2, j can be 0, 1 or 2. At step i = 1, j can be 0 or 1. That gives 3 × 2 = 6 choice sequences.
| Choice at i = 2 | After step i = 2 | Choice at i = 1 | Final result |
|---|---|---|---|
| j = 0 | C B A | j = 0 | B C A |
| j = 0 | C B A | j = 1 | C B A |
| j = 1 | A C B | j = 0 | C A B |
| j = 1 | A C B | j = 1 | A C B |
| j = 2 | A B C | j = 0 | B A C |
| j = 2 | A B C | j = 1 | A B C |
All six final results are different, and together they are the six permutations of three items. Each one has probability 1/3 × 1/2 = 1/6.
A table works for n = 3, but the claim has to hold for every n. The next two sections give two general proofs. Each one is useful in a different way.
Proof 1: Recovering the choices from the output
To show that the map is one-to-one, it is enough to show that the choice sequence can be reconstructed from the final permutation. If you can always decode the output, no two sequences can share it.
The key fact is this: after step i, position i is never written again. Later steps only swap positions at index i − 1 or below. The element that ends up at position i is therefore the one placed there at step i, and so j at step i was wherever that element sat just before step i.
Decoding follows directly. Replay the algorithm from the original list. At each step i, look up where the target's element final[i] currently is. That index is the j that was chosen. Perform the swap and continue.
def recover_choices(n, final):
"""Given the output of Fisher-Yates on range(n), return the j at each step."""
current = list(range(n))
choices = []
for i in range(n - 1, 0, -1):
j = current.index(final[i])
assert j <= i # positions above i are already fixed and match final
choices.append(j)
current[i], current[j] = current[j], current[i]
assert current == list(final)
return choices
print(recover_choices(4, [2, 0, 3, 1])) # [1, 0, 1]The assert j <= i always passes. Positions i + 1 through n − 1 already hold final[i+1:], so final[i] cannot be among them and must sit at index i or below. Every decoded j is therefore a legal choice for its step. This means decoding works for any permutation, not only those you have actually observed. So the map is onto as well as one-to-one, and that confirms the bijection.
Proof 2: Induction on n
The second proof explains why the algorithm works, not only that the counting adds up.
Claim. For any input list of n distinct items, in any starting order, Fisher-Yates returns each of the n! permutations with probability 1/n!.
Base case. For n = 1 the loop does not run. There is one permutation, and it has probability 1 = 1/1!.
Inductive step. Assume the claim holds for lists of length n − 1. Take a list of length n and any target permutation π. Let x be the element that π puts in the last position.
- At step i = n − 1,
jis uniform over 0..n−1. Exactly one value ofjmoves x into position n − 1, so this happens with probability 1/n. - After that swap, position n − 1 is never touched again. The remaining steps (i = n − 2 down to 1) are exactly Fisher-Yates applied to the prefix
items[0..n-2], which holds the other n − 1 elements in some order. - By the inductive hypothesis, that prefix comes out in the order π requires with probability 1/(n−1)!. This holds whatever order the prefix was left in, because the hypothesis covers every starting order.
- The later draws are independent of the first one, so the probabilities multiply: 1/n × 1/(n−1)! = 1/n!.
Point 3 is the subtle one. The first swap rearranges the prefix differently depending on j. For example, if j = 0, the old last element moves to the front. That does not matter, because a uniform shuffle of n − 1 items stays uniform regardless of how they started.
Checking the bijection by brute force
The proofs cover all n. For small n you can also confirm the bijection by enumerating every choice sequence instead of sampling random ones. This makes a good regression test for any change to the loop bounds.
from collections import Counter
from itertools import product
from math import factorial
def shuffle_with_choices(n, choices):
items = list(range(n))
for i, j in zip(range(n - 1, 0, -1), choices):
items[i], items[j] = items[j], items[i]
return tuple(items)
def check_fisher_yates(n):
ranges = [range(i + 1) for i in range(n - 1, 0, -1)] # sizes n, n-1, ..., 2
outcomes = Counter(shuffle_with_choices(n, c) for c in product(*ranges))
sequences = sum(outcomes.values())
print(f"n={n}: {sequences} sequences, {len(outcomes)} distinct permutations, "
f"n! = {factorial(n)}, every count is 1: {set(outcomes.values()) == {1}}")
for n in range(1, 8):
check_fisher_yates(n)For every n up to 7, the script reports n! sequences, n! distinct permutations, and a count of exactly 1 for each. That is the bijection, checked exhaustively.
What the proof assumes
A proof only guarantees fairness while its assumptions hold. The proof above relies on three of them.
| Assumption | Where the proof uses it | What breaks it |
|---|---|---|
| The range at step i has exactly i + 1 values, 0..i | The sequence count is exactly n! | Off-by-one bounds (next chapter) |
| Each draw is exactly uniform over its range | Each sequence has probability 1/n! | Modulo bias in random integer generation |
| Draws are independent, and every sequence is reachable | Probabilities multiply, and the bijection covers all n! sequences | A PRNG with too few internal states |
Each row matches a later chapter. If you change the range to 0..i-1, there are only (n−1)! sequences, so some permutations become unreachable. This variant is Sattolo's algorithm. If you change it to 0..n-1, you are back to n^n sequences and the collisions return. The algorithm itself is correct. Real implementations fail when one of these three inputs is wrong.
Exercises
Exercise
Use the recovery procedure on the output [1, 2, 0] from shuffling [0, 1, 2]. Which choice sequence (j at i = 2, then j at i = 1) produced it? Check your answer against the n = 3 table.
Show answer
Start with current = [0, 1, 2]. At i = 2, final[2] = 0 is at index 0, so j = 0. Swapping gives [2, 1, 0]. At i = 1, final[1] = 2 is at index 0, so j = 0. Swapping gives [1, 2, 0], which matches. The choices are (0, 0). In the table's letters this is A→0, B→1, C→2, and the row "j = 0, j = 0" gives B C A, which is [1, 2, 0].
Exercise
In the inductive proof, step 3 depends on the hypothesis holding for any starting order of the prefix. Why would a weaker hypothesis, "Fisher-Yates is uniform when the input starts in sorted order", not be enough?
Show answer
After the first swap, the prefix is in an order that depends on j. It is usually not sorted. For example, with j = 0 the old last element moves to index 0. To apply the hypothesis to the prefix, it has to cover whatever order the prefix is left in, so the stronger "any starting order" statement is needed. The proof still goes through, because the base case and the inductive step never rely on the input being sorted.
Exercise
Suppose someone writes j = random.randint(0, i - 1) for i from n − 1 down to 1. Using the counting argument from this chapter, how many choice sequences are there for n = 4, and what does that tell you about fairness?
Show answer
The range sizes are 3, 2 and 1, so there are 3 × 2 × 1 = 6 = (n−1)! sequences. There are 4! = 24 permutations, so at most 6 of them can ever appear and the shuffle cannot be uniform. In fact the identity permutation never appears, because every step moves the element at position i. This is Sattolo's algorithm, which produces only single-cycle permutations.