Sub topic 7
Cost: O(n) Time, O(1) Extra Space
This chapter measures what the in-place Fisher-Yates shuffle costs in time, memory, and random bits, and compares it with the alternatives you might reach for instead. It assumes you already know the Durstenfeld loop from the earlier chapter, can read Big-O notation (O(n), O(n log n), O(n²)), and are comfortable with Python lists.
Counting the Work in the Loop
Here is the shuffle again, with counters added so you can see the work it does:
import random
def fisher_yates_counted(items):
swaps = 0
draws = 0
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i)
draws += 1
items[i], items[j] = items[j], items[i]
swaps += 1
return items, swaps, draws
for n in (10, 100, 1000, 10000):
_, swaps, draws = fisher_yates_counted(list(range(n)))
print(f"n={n:>6} swaps={swaps:>6} random draws={draws:>6}")The loop runs once for each i from n - 1 down to 1, which is exactly n - 1 iterations. Each iteration does three things:
- It draws one random integer.
- It reads two array slots.
- It writes two array slots.
None of these depends on n, so each iteration costs O(1) and the whole shuffle costs O(n). The count is also exact: there is no best case or worst case. Every run on an array of length n does the same n - 1 iterations, whatever the input and whatever random values come out.
Self-swaps
Sometimes j == i, and the element is swapped with itself. That happens with probability 1/(i+1) at step i, so the expected number of self-swaps is about ln n. That is roughly 7 for a million elements. Adding an if j != i test to skip them almost never helps. The branch runs on every iteration and saves only a handful of them.
Extra Space: Three Variables
The in-place version needs only the loop index i, the random index j, and whatever the language uses to hold one value during the swap. That is O(1) extra space. The shuffle does not recurse, build a buffer, or allocate anything proportional to n.
In CPython, the tuple-style swap items[i], items[j] = items[j], items[i] compiles to a stack operation and does not create a tuple object, so the swap really is constant space.
Why the Original 1938 Method Is Slower
The pencil-and-paper method repeatedly picks a random number k, walks through the list to find the k-th element that has not been struck out yet, and writes it down. A straightforward program version removes the chosen element from a list:
import random
def original_method(items):
remaining = list(items)
result = []
while remaining:
k = random.randrange(len(remaining))
result.append(remaining.pop(k)) # shifts every element after k
return result
print(original_method(range(10)))The output is just as fair as Durstenfeld's, but each pop(k) shifts every element after position k one place to the left. On average that moves about half of the remaining elements. Added up over all n picks, that is about n²/4 element moves, so the method is O(n²). Doing the striking out by hand has the same quadratic cost, because you scan past struck-out entries to find the k-th live one.
Durstenfeld's insight was to avoid deleting anything. Swapping the chosen element into the end of the array puts the "struck out" region and the "remaining" region side by side, and the boundary between them is just the index i.
You can watch the difference on your own machine:
import random
import time
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i)
items[i], items[j] = items[j], items[i]
return items
def original_method(items):
remaining = list(items)
result = []
while remaining:
k = random.randrange(len(remaining))
result.append(remaining.pop(k))
return result
for n in (25_000, 50_000, 100_000, 200_000):
data = list(range(n))
t0 = time.perf_counter()
fisher_yates(data[:])
t1 = time.perf_counter()
original_method(data)
t2 = time.perf_counter()
print(f"n={n:>7} in-place={t1 - t0:.3f}s original={t2 - t1:.3f}s")Each time n doubles, the in-place time should roughly double. The original method's time should grow toward four times as much. For small n the gap can look narrow, because CPython's pop shifts elements with a fast C memmove. The quadratic term takes over as n grows.
The Cost of Randomness
Big-O counts each random draw as one step, but in practice the draws are usually the most expensive part of the loop.
Draws per index
An unbiased integer in [0, i] is usually produced by rejection sampling. The generator draws enough random bits to cover the range and throws the value away if it falls outside. Python's randint works like this. In the worst case, just over half of the raw values are rejected, so the expected number of raw draws per index is always below 2. The total is still O(n) expected, but an individual run has no fixed upper bound. If you need hard real-time guarantees, that matters. For everything else it doesn't.
Bits consumed
Choosing one permutation out of n! needs at least log2(n!) bits of information, which is roughly n log2 n bits. Fisher-Yates uses about ceil(log2(i+1)) bits at step i, plus whatever rejection wastes, which is close to that lower bound. This is the real reason the shuffle is "linear": it counts array operations. Measured in random bits, every fair shuffle needs Θ(n log n) bits. The chapter on generator state size returns to what happens when the generator cannot supply that many distinct bits.
Cryptographic generators
A cryptographically secure generator such as random.SystemRandom or crypto.getRandomValues can be many times slower per draw than a fast generator like Mersenne Twister. The shuffle stays O(n), but the constant factor changes. Batching, for example filling a Uint32Array with many values at once, reduces the per-call overhead.
Memory Access on Large Arrays
Every iteration touches items[i], which moves sequentially, and items[j], which lands anywhere in the unshuffled prefix. Once the array is larger than the CPU cache, almost every items[j] access is a cache miss. Shuffling a hundred million integers therefore spends most of its time waiting on memory, not computing. In Python, a list holds pointers to objects that may themselves be scattered in memory, so reading the shuffled list later is also slow. This is a constant-factor effect and does not change O(n), but it explains why measured time per element rises once the data outgrows the cache.
Comparing the Alternatives
| Approach | Time | Extra space | Fair? |
|---|---|---|---|
| In-place Fisher-Yates | O(n) | O(1) | Yes |
| Original 1938 method (list removal) | O(n²) | O(n) | Yes |
| Inside-out variant | O(n) | O(n) for the output | Yes |
| Sort by random keys | O(n log n) | O(n) for keys | Only if no keys tie |
| Sort with a random comparator | O(n log n) or worse | Depends on sort | No |
| Partial shuffle of k items | O(k) | O(1) | Yes |
Sorting by random keys is a common one-liner, such as sorted(items, key=lambda _: random.random()). It is fair as long as no two keys are equal, but it costs a log factor and an extra array of keys. A comparator that returns random answers, such as JavaScript's arr.sort(() => Math.random() - 0.5), is worse. It breaks the sort's assumption of a consistent ordering, so the result is biased in ways that depend on the sort algorithm, and some sort implementations do extra work or misbehave.
Summary of the Cost Model
- The loop does exactly
n - 1iterations, each with one random draw and one swap. - In-place Fisher-Yates uses O(1) extra space. Keeping the input intact adds an O(n) copy.
- The original method is O(n²) because of deletion or scanning. Swapping into the tail removes that cost.
- Random draws dominate the constant factor. Rejection sampling averages fewer than 2 raw draws per index.
- Any fair shuffle needs about
n log2 nrandom bits, however few array operations it does.
Exercise
A colleague shuffles a 10,000-element list by repeatedly calling random.choice(remaining), appending the result to the output, and then calling remaining.remove(value). What is the time complexity, and why?
Show answer
O(n²). random.choice is O(1), but remaining.remove(value) first searches the list for the value (O(n)) and then shifts the elements after it (O(n)). Doing that n times gives O(n²) total. It also gives wrong results if the list contains duplicates. Durstenfeld's in-place swap avoids both the search and the shift.
Exercise
Fisher-Yates is described as O(n), but a fair shuffle needs about log2(n!) random bits. Is that a contradiction?
Show answer
No. O(n) counts loop iterations and swaps, each treated as constant time. Each iteration draws an index that takes about log2(i+1) bits, so the bits consumed total about log2(n!), which is Θ(n log n). On real hardware one machine word supplies those bits, so each draw still costs constant time until n becomes astronomically large.
Exercise
You must shuffle a list that the caller will keep using in its original order. Compare copying it and then running in-place Fisher-Yates with running the inside-out variant.
Show answer
Both take O(n) time and O(n) extra space, because either way a new list of n elements is needed. The copy-then-shuffle approach reads the input in one pass and then makes a second pass with random access. The inside-out variant does both in a single pass and also works when the input is a stream or iterator whose length is not known in advance.