Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Randomization

The Fair Shuffle.

Watch the explainer

Shuffling looks trivial until you get it subtly wrong — and the "obvious" shuffle (for each slot, swap it with any random slot) is biased, favouring some orderings over others. Fisher–Yates does it right: walk from the last slot toward the first, and swap each element with a random one chosen only from the part not yet finalized. Every one of the n! orderings comes out equally likely, in a single O(n) pass. Step through it and watch the finalized region grow.

O(n) time · O(1) extra space · provably uniform over all n! permutations
unshuffled region

The front slots 0..i not yet finalized — the only place a swap partner is drawn from.

finalized region

The back slots i+1..n−1, already locked to their final values.

swap i ↔ j

Pick random j in [0, i], swap, then shrink i by one.

uniform

Every one of the n! orderings ends up equally likely.

shuffle.js — swap from the back, pick from the front
Ready
An array of 8 cards. We walk i from the last slot toward the first. At each step we pick a random j in [0, i] and swap — locking slot i to its final value.
7
cursor i
–
picked j
0
locked

How it works

The correctness rests on one careful choice: the random partner j is drawn from [0, i] — the unshuffled region including i itself — never from the whole array. That single constraint is what makes the result uniform. The naive version that draws j from [0, n−1] looks almost identical and is quietly, provably biased.

1

Start at the last slot

Set the cursor i to n−1. Everything to its left is still up for grabs; nothing is finalized yet.

2

Swap with a random earlier (or equal) slot

Pick j uniformly in [0, i], swap a[i] and a[j]. Slot i now holds a uniformly-chosen element from the unshuffled region — and it is locked forever.

3

Shrink and repeat

Move i one step left and repeat, always drawing j only from the still-unshuffled prefix. When i reaches 0, the whole array is a uniform permutation.

✓

Why not draw j from the whole array?

The naive shuffle draws j from [0, n−1] every time. It produces n^n equally-likely execution paths, and n^n is not divisible by n! — so some orderings are strictly more likely than others. Fisher–Yates produces exactly n! paths, one per permutation.

Time
O(n)
Extra space
O(1)
Outcomes
n! equally likely
Naive bias
n^n ≠ k·n!

The code

# the modern (Durstenfeld) Fisher-Yates, in place, O(n) def shuffle(a): for i in range(len(a) - 1, 0, -1): # from the back j = random.randint(0, i) # j in [0, i] <- the key line a[i], a[j] = a[j], a[i] # swap, lock slot i return a # BIASED — do NOT do this: j spans the whole array every time # for i in range(len(a)): j = randint(0, len(a)-1); swap(a[i], a[j])

Quick check

1. Where must the random index j be drawn from at step i?

2. Why is the naive shuffle (j from [0, n−1] each step) biased?

3. What is the time and extra-space cost of Fisher–Yates?

FAQ

What is the Fisher–Yates shuffle?

An algorithm that randomly permutes an array so all n! orderings are equally likely, in O(n) time and O(1) extra space. It walks from the last element to the first, swapping each with a random element from the not-yet-finalized portion.

Why is the naive shuffle biased?

It swaps each index with a random index from the entire array, making n^n equally-likely paths. Since n^n is not divisible by n! (for n > 2), those paths can’t spread evenly over the n! orderings — some come up more often.

Is Fisher–Yates the same as shuffling by sorting on random keys?

Sorting on random keys can also give a uniform shuffle (with distinct keys), but it costs O(n log n) and needs careful tie-breaking. Fisher–Yates is simpler, O(n), and in place — the standard choice.

Does the quality of the random number generator matter?

Yes — it’s only as uniform as its RNG. A weak or small-state generator makes many permutations unreachable; a 32-bit seed cannot produce most orderings of a 52-card deck, since 52! far exceeds 2^32. Use a high-quality RNG when fairness matters.

The picture: counting paths to each ordering

Naive: 27 equally likely pathsFisher-Yates: 6 paths4012101250211021510211025120112042011201421012104.5
Every random choice sequence the shuffle can make, counted by the ordering it ends in, for three items 0 1 2 (orderings written as digit strings). The naive loop, which swaps each slot with any slot, has 3 × 3 × 3 = 27 paths. They cannot split evenly into 6 orderings, so three orderings get 5 paths and three get 4. Fisher-Yates has 3 × 2 × 1 = 6 paths, one per ordering. The line is the ideal 27 / 6 = 4.5.

Worked example, step by step

Shuffle ['a', 'b', 'c', 'd', 'e'] with Fisher-Yates, using these four random draws, in order: 1, 3, 0, 1. Step t works on i = 5 − t, draws j = rand(i + 1) in [0, i], swaps a[i] with a[j] and locks slot i (shown in brackets).

StepSlotDrawSwapArray (locked in brackets)
start–––a b c d e
1i = 4rand(5) = 1swap a[4] (e) with a[1] (b)a e c d [b]
2i = 3rand(4) = 3swap a[3] with itselfa e c [d] [b]
3i = 2rand(3) = 0swap a[2] (c) with a[0] (a)c e [a] [d] [b]
4i = 1rand(2) = 1swap a[1] with itselfc [e] [a] [d] [b]

The shuffled result is c e a d b. Step 2 shows the case people forget: the draw was 3, which equals i, so the element stays where it is, and that is correct and necessary. If a slot were never allowed to keep its element, no ordering could leave an item in place. Also notice that the draws came from shrinking ranges, 5 then 4 then 3 then 2 values, so the number of possible draw sequences is 5 × 4 × 3 × 2 = 120, which is exactly 5!. I ran all 120 sequences: they produce 120 different orderings, each exactly once. That is the whole proof of uniformity: a one-to-one match between random choices and permutations. The last slot, slot 0, needs no draw because only one element remains.

Common mistakes

  • Swapping with any slot (the naive shuffle)

    Counting every path: for 3 items the orderings occur 4, 5, 5, 5, 4, 4 times out of 27. For 4 items, the 24 orderings occur between 8 and 15 times out of 256, against an even 10.67; 1 0 3 2 is the most likely ordering and 3 0 1 2 is among the least. For 5 items the range is 16 to 47 out of 3,125, against 26.04.

  • Drawing j from [0, i−1] instead of [0, i]

    An off-by-one in the range removes the "stay put" outcome. For 4 items that version produces only 6 distinct orderings out of 24, and in every one of them no item is in its original place (1 2 3 0, 2 3 0 1, ...). This is Sattolo's algorithm, which is correct when you want a single cycle, and a bug when you want a shuffle.

  • Using a modulus on a generator whose range is not a multiple of n

    If the generator returns a byte in 0..255 and you take x % 10, the values 0 to 5 each have 26 ways to occur and 6 to 9 have 25. Small, but every draw is slightly skewed. Use the library's bounded-integer function, or reject values from the incomplete top block.

  • A seed that is too small

    A generator seeded with 32 bits can start in at most 2³² states, so it can reach at most 4,294,967,296 orderings. 12! is 479,001,600, which fits; 13! is 6,227,020,800, which does not. A 13-item shuffle from a 32-bit seed can therefore reach at most 69% of the orderings (4,294,967,296 / 6,227,020,800), and a 14-item one at most 4.9%, however correct the loop is. A 52-card deck has 52! orderings, a 68-digit number starting 806.

  • Shuffling with a random comparator

    arr.sort(() => Math.random() − 0.5) is not a shuffle, because sorting algorithms assume a consistent comparator. On Node v22.20.0, shuffling [1, 2, 3] 600,000 times gave 1 2 3 224,773 times and 1 3 2 only 37,540 times, where an even shuffle gives 100,000 each. Other engines may differ; the result depends on the sort implementation and is not guaranteed uniform.

Where this shows up

  • Standard libraries

    Python's random.shuffle is this algorithm: it walks i from the last index down to 1 and swaps with a j drawn from i + 1 choices. If you are not writing a shuffle for practice, call the library one.

  • Card games and lotteries

    Shuffling a deck, or drawing a random order for a draw, needs every ordering to be possible and equally likely, which is why both the loop and the quality of the generator matter.

  • Machine learning data order

    Training loops reshuffle the data each epoch so that batches are not in a fixed, possibly correlated order. Stopping Fisher-Yates after k steps also gives k random items drawn without replacement, in O(k).

  • Secret Santa and cyclic assignments

    Sattolo's variant, the off-by-one mistake above done on purpose, produces a single cycle. Used to assign gifts, it guarantees that nobody draws their own name.

Complexity and trade-offs

CaseTimeSpaceWhy
Fisher-YatesO(n)O(1) extran − 1 random draws and swaps: 999 for n = 1,000. Uniform.
Sort by random keysO(n log n)O(n)Needs a key per item; sorting 1,000 keys took 8,605 comparisons. Uniform only if keys are distinct.
Pick and remove from a listO(n²)O(n)Each removal shifts the tail: 249,048 element moves for n = 1,000. Uniform, but slow.
Naive swap with any slotO(n)O(1) extraSame speed as Fisher-Yates and biased, so it has no advantage.

Fisher-Yates is both the fastest and the smallest here, so there is almost nothing to trade off: it is the default unless you need a shuffle that does not modify the input, in which case copy first at O(n) space. The random-key sort is the one to reach for only when the data is already being sorted or the shuffle must be done by a system whose only primitive is an ordered sort. The counts above are for one run on 1,000 items; the growth rates, n versus n log n versus n², are what carry over.

SOLVE IT YOURSELF

Solve it: shuffle without bias

The obvious shuffle — walk the array and swap each element with a random index — is wrong, and produces some orderings more often than others. The correct version differs by one character. Write it in Python or TypeScript.

YOUR TASK

Implement shuffle(items, rand): return a shuffled copy. rand(n) returns an integer in [0, n) and is passed in, so the result is deterministic and testable.

HINTS — 5 IDEAS
  1. Walk i from the last index down to 1.
  2. At each step pick j = rand(i + 1) — a random index from the unshuffled prefix, including i itself — and swap.
  3. The critical detail: the range is [0, i], not [0, n). Picking from the whole array each time is the classic biased shuffle.
  4. Why bias creeps in: the naive version can produce nⁿ equally-likely execution paths, but there are only n! permutations — and nⁿ is not divisible by n!, so some orderings must come up more often.
  5. The correct version makes exactly n! paths, one per permutation. Stopping at i > 0 is fine: index 0 has only itself left to choose.
CPython · WebAssembly
▶  Watch it explained

Fisher-Yates Shuffle: Time and Space Complexity, From First Principles

Keep going

Finished this one? 0 / 99 Algorithms done
NextThe Fair Draw: Reservoir Sampling Next on the “One pass, constant space” ladder · rung 3 of 3

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms