Sub topic 7
Cost: O(n) Time, O(1) Extra Space
This chapter assumes you have read the in-place Fisher-Yates shuffle from the previous chapter, know Big-O notation, and can read short Python loops. Here we count the work the algorithm does and compare it with the 1938 pencil-and-paper method and with the "sort by random keys" shortcut.
Counting the Work
Durstenfeld's version runs its loop once for each index from n - 1 down to 1. That gives n - 1 iterations. Each iteration does a fixed amount of work:
- It draws one random integer
jin the range[0, i]. - It swaps
items[i]anditems[j].
No step depends on how many elements are left, so the total time is O(n). The only extra memory is the loop variable i, the index j, and one temporary value for the swap. That is O(1) extra space, because the list is shuffled in place.
The following script counts the operations directly:
import random
def fisher_yates_counted(items):
draws = swaps = 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 draws, swaps
for n in (10, 1000, 100000):
print(n, fisher_yates_counted(list(range(n))))For every n, the script prints n - 1 draws and n - 1 swaps. The work grows in a straight line with the input size.
Why the Original Method Is Slower
In Fisher and Yates's 1938 method, you pick a random number k and then count along the list to the k-th number that has not yet been struck out. Finding that number means scanning the list, which costs O(n) per step. Over n steps that adds up to O(n²).
import random
def original_method_steps(n):
remaining = list(range(n))
steps = 0
while remaining:
k = random.randrange(len(remaining))
steps += k + 1 # walk to the k-th unstruck number
remaining.pop(k) # strike it out
return steps
for n in (10, 1000, 10000):
print(n, original_method_steps(n))The step count comes out near n² / 4: about 25 for n = 10 and about 25 million for n = 10000. Durstenfeld removed this cost by moving each chosen element to the end of the array. The "unstruck" elements then always sit in one block at the front, so any of them can be reached by index in O(1).
Comparison with Other Approaches
| Method | Time | Extra space | Uniform? |
|---|---|---|---|
| Original 1938 method (strike out) | O(n²) | O(n) for the output list | Yes |
| Durstenfeld in-place Fisher-Yates | O(n) | O(1) | Yes |
| Sort by random keys | O(n log n) | O(n) for the keys | Only if keys never tie |
| Sort with a random comparator | O(n log n) | Depends on the sort | No, biased |
Sorting by random keys gives each element a random number and sorts by it. It works when the keys are distinct, but it costs a log factor and an extra array. The random-comparator trick, such as arr.sort(() => Math.random() - 0.5) in JavaScript, is worse because it breaks the sort's assumption that comparisons are consistent, and its output is biased.
Common Mistakes
- Copying the list first and calling it in place. Writing
items = list(items)at the top of the function is fine if you need a copy, but it brings back O(n) extra space. - Removing elements from the middle of a list. Calling
list.pop(k)orremoveinside the loop shifts the remaining elements each time. That quietly turns an O(n) shuffle back into the O(n²) original method. - Assuming the random source is free. A slow cryptographic generator changes the constant factor but not the O(n) growth.
Exercise
A colleague writes a shuffle that, for each step, picks a random index k into a list called pool, appends pool[k] to a result list, and calls pool.pop(k). What are its time and extra-space costs, and how would you change it to reach O(n) time and O(1) extra space?
Show answer
Each pool.pop(k) shifts every element after k, which costs O(n) per step, so the whole shuffle takes O(n²) time. The pool and result lists together use O(n) extra space. To fix it, shuffle the original array in place: for i from n-1 down to 1, choose j uniformly from [0, i] and swap items[i] with items[j]. That is n-1 constant-time steps with only i, j, and a temporary value as extra storage.