Is This Playlist Shuffle Actually Fair?
Statistics & ExperimentsModel answerLast updated
Determine whether a naive shuffle that always picks from the full array produces a uniform distribution, and explain why or why not using probability theory.
Background
A junior engineer on your team built a playlist shuffler. Rather than using the textbook approach, they wrote their own version:
def playlist_shuffle(arr):
n = len(arr)
for i in range(n):
# Swap element i with any position in the full array
j = random.randint(0, n - 1)
arr[i], arr[j] = arr[j], arr[i]
return arr
You're asked to audit this implementation before it ships.
Your Tasks
-
Probability Analysis: Does this algorithm generate each possible ordering with equal probability? Construct a mathematical argument. If the distribution is not uniform, explain precisely why.
-
Complexity: What are the time and space complexities of this function?
-
RNG Quality: Set the correctness of the algorithm aside for a moment. What practical issues with the underlying random number generator could degrade shuffle quality even further?
-
Fairness Testing: Propose one or more concrete methods to verify whether any shuffle implementation is statistically unbiased.
Constraints
- Treat
random.randint(a, b)as producing a perfectly uniform integer in[a, b]. - Use small cases (e.g.
n = 3) to build your argument before generalizing.
Worked Example
For the array [A, B, C] (n = 3):
- Each of the 3 iterations picks independently from 3 positions.
- There are
3³ = 27equally likely sequences of choices in total. - There are
3! = 6possible orderings. - For the distribution to be uniform, each ordering would need to be produced by exactly
27 / 6 = 4.5choice sequences.
What does that tell you?
Hints
Hint 1
Count the total number of equally likely execution paths (n^n) and the number of permutations (n!). For the shuffle to be uniform, the first number must divide the second evenly — check whether that's guaranteed.
Hint 2
For n = 3, manually trace a few choice sequences to see which orderings are over-represented and which are under-represented. This concrete enumeration turns the abstract argument into something you can show.
Hint 3
Fisher-Yates avoids this problem by restricting the random draw to the not-yet-finalized portion of the array. Think about how that changes the path-count arithmetic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Argument: Path Counting
The key insight is a counting argument, and it should come before any simulation or code.
Each iteration independently picks one of n indices, so the algorithm has n^n equally likely execution paths. Each path produces exactly one permutation. For the output distribution to be uniform, every permutation must be produced by the same number of paths, which means n^n / n! must be a whole number.
For n = 3: 27 / 6 = 4.5 — not an integer. The shuffle cannot be uniform.
This generalizes. For any n ≥ 3, the prime (n − 1) divides n! but shares no factor with n^n (since gcd(n − 1, n) = 1). So n! never divides n^n, and the algorithm is biased for every n ≥ 3.
Small exceptions: n = 1 is trivially fine. n = 2 happens to work because 4 / 2 = 2. This means a test suite that only checks pairs of elements will incorrectly pass this code — a common mistake.
Concrete Enumeration for n = 3
Enumerating all 27 choice sequences on [1, 2, 3]:
| Ordering | Paths | Probability | Fair value |
|---|---|---|---|
| [1, 2, 3] | 4 | 4/27 ≈ 0.148 | 1/6 ≈ 0.167 |
| [1, 3, 2] | 5 | 5/27 ≈ 0.185 | 1/6 ≈ 0.167 |
| [2, 1, 3] | 5 | 5/27 ≈ 0.185 | 1/6 ≈ 0.167 |
| [2, 3, 1] | 5 | 5/27 ≈ 0.185 | 1/6 ≈ 0.167 |
| [3, 1, 2] | 4 | 4/27 ≈ 0.148 | 1/6 ≈ 0.167 |
| [3, 2, 1] | 4 | 4/27 ≈ 0.148 | 1/6 ≈ 0.167 |
The bias also shows up per-position. Element 2 lands in slot 0 with probability 10/27, element 1 with 9/27, element 3 with 8/27. A fair shuffle would give each element a 9/27 chance at every slot.
Why the skew happens. An element displaced in step i can be swapped back in a later step. Different permutations are reachable through different numbers of these "undo" paths, so they accumulate unequal weights.
The fix. Fisher-Yates draws j only from [i, n − 1] at step i, so each finalized slot is never touched again. That gives exactly n! paths — one per permutation — each with probability 1/n!. The time and space complexity are the same O(n) / O(1), so there is no cost to doing it correctly.
Complexity
- Time: O(n). One RNG call and one swap per iteration.
- Space: O(1) auxiliary. The shuffle is in-place; the function also mutates its input, which callers should be aware of.
Practical RNG Concerns
Even if the algorithm were corrected, the random number generator itself can introduce problems:
Modulo bias. Code like rand() % n in C or JavaScript is non-uniform when n doesn't divide the RNG's output range. Some values get one extra preimage. Python's random.randint avoids this internally via rejection sampling, but hand-ports to other languages frequently reintroduce it. The fix is rejection sampling or Lemire's fast method.
State-space exhaustion. A PRNG with b bits of internal state can produce at most 2^b distinct shuffle sequences. Python's Mersenne Twister has ~19,937 bits of state, which sounds like a lot until you realize that 2081! > 2^19937 — so most permutations of a playlist with more than ~2,000 songs are simply unreachable. Seeding from a 32-bit value makes this far worse, capping you at 2^32 possible outputs regardless of playlist size.
Predictability. MT19937 can be fully reconstructed after observing 624 outputs. For anything with real stakes — game item drops, A/B test assignment, shuffle-based lotteries — use secrets.SystemRandom(), which draws from the OS entropy pool.
Testing for Fairness
Exact enumeration (small n). Replace the RNG with every possible choice sequence deterministically and count outcomes. For n = 3 or n = 4 this is fully tractable and gives proof, not statistics.
Chi-square over permutations. For small n (say n = 4, so 24 bins), run ~1,000,000 shuffles and compare observed counts against the expected trials / n! using a chi-square test with n! − 1 degrees of freedom. Decide your significance threshold before looking at the data.
Position frequency matrix (larger n). Track how often each element lands in each slot. Each cell should be approximately trials / n. A chi-square test on this matrix catches marginal bias and scales to larger n where enumerating all permutations is infeasible. Note: uniform marginals are necessary but not sufficient — a deterministic cyclic rotation passes this test.
Distribution statistics. Compare against known theoretical values for a uniform shuffle: the expected number of fixed points is ~1 (Poisson(1)), the expected number of inversions is n(n−1)/4, and the expected length of the longest increasing subsequence is approximately 2√n. Large deviations from these are a signal worth investigating.
Implementation
import itertools
import math
import random
from collections import Counter
def audited_shuffle(arr, choices):
"""Run the audited algorithm with a fixed choice sequence for enumeration."""
a = list(arr)
for i, j in enumerate(choices):
a[i], a[j] = a[j], a[i]
return tuple(a)
def exact_path_distribution(n):
"""Enumerate all n^n paths; return a Counter mapping permutation -> path count."""
base = list(range(1, n + 1))
counts = Counter()
for choices in itertools.product(range(n), repeat=n):
counts[audited_shuffle(base, choices)] += 1
return counts
def is_divisible(n):
"""Necessary condition for uniformity: n^n must be divisible by n!."""
return (n ** n) % math.factorial(n) == 0
def fisher_yates(arr):
"""Correct uniform shuffle: O(n) time, O(1) space."""
for i in range(len(arr) - 1, 0, -1):
j = random.randint(0, i) # draw only from the unfixed region
arr[i], arr[j] = arr[j], arr[i]
return arr
def chi_square_test(shuffle_fn, n, trials=500_000):
"""
Run shuffle_fn `trials` times on range(n) and compute chi-square
statistic against a uniform distribution over all n! permutations.
Returns (statistic, degrees_of_freedom).
"""
counts = Counter(
tuple(shuffle_fn(list(range(n)))) for _ in range(trials)
)
expected = trials / math.factorial(n)
stat = sum(
(counts.get(p, 0) - expected) ** 2 / expected
for p in itertools.permutations(range(n))
)
return stat, math.factorial(n) - 1
if __name__ == "__main__":
# Exact distribution for n=3 — shows the 4/5 split
dist = exact_path_distribution(3)
for perm in sorted(dist):
print(f"{perm}: {dist[perm]}/27")
# n=1 and n=2 pass the divisibility check; n>=3 all fail
uniform_cases = [n for n in range(1, 9) if is_divisible(n)]
print("Uniform for n in:", uniform_cases) # [1, 2]
Common Mistakes to Avoid
- Testing only on n = 2. The buggy algorithm is coincidentally fair there; always test n = 3 or larger.
- Stopping at "it looks random." Eyeballing output or checking that each element appears roughly the same number of times is not a bias test — uniform marginals don't imply a uniform joint distribution.
- Assuming the RNG is the only problem. Even a perfect RNG can't fix a structurally biased algorithm.
- Forgetting mutation. This function modifies its argument in place. If the caller holds a reference to the original list, they will see the shuffled version.