Design Data Structures · Pattern 7 of 10
Randomized algorithms: a fair shuffle
Fisher-Yates walks from the end and swaps each position with a random position at or before it. Every one of the n! orders comes out with the same chance, in O(n).
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Return a random order (or a random sample) where every outcome is equally likely
- Reset back to the original input
- Pick k items uniformly, maybe from a stream
The template
class Solution {
int[] original;
Random rnd = new Random();
Solution(int[] nums) { original = nums.clone(); }
int[] reset() { return original.clone(); } // a copy: callers cannot change it
int[] shuffle() {
int[] a = original.clone();
for (int i = a.length - 1; i > 0; i--) {
int j = rnd.nextInt(i + 1); // any index in [0, i], including i
int t = a[i]; a[i] = a[j]; a[j] = t;
}
return a;
}
} import random
class Solution:
def __init__(self, nums):
self.original = nums[:]
def reset(self):
return self.original[:] # a copy: callers cannot change it
def shuffle(self):
a = self.original[:]
for i in range(len(a) - 1, 0, -1):
j = random.randint(0, i) # any index in [0, i], including i
a[i], a[j] = a[j], a[i]
return a class Solution {
vector<int> original;
mt19937 rng{random_device{}()};
public:
Solution(vector<int>& nums) : original(nums) {}
vector<int> reset() { return original; } // returned by value: a copy
vector<int> shuffle() {
vector<int> a = original;
for (int i = (int)a.size() - 1; i > 0; i--) {
int j = uniform_int_distribution<int>(0, i)(rng); // any index in [0, i]
swap(a[i], a[j]);
}
return a;
}
}; class Solution {
constructor(nums) { this.original = [...nums]; }
reset() { return [...this.original]; } // a copy: callers cannot change it
shuffle() {
const a = [...this.original];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // any index in [0, i], including i
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
} The variations
-
1Fisher-Yates shuffle
Position
igets a random item from the ones not placed yet (indexes 0..i), and that choice is never touched again. That gives n choices, then n − 1, and so on: exactly n! equally likely outcomes. Keep the original separately soresetis a copy. -
2More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Picking
jfrom the whole array on every step: it looks random but some orders come up more often than others. - Picking
jfrom[0, i - 1], which never leaves an item in place: also biased. - Shuffling the stored array itself, so
resetreturns the shuffled order.
Lesson done
Next: Dependency graphs: formulas that update →Mark it done once you can write the template from memory and you have solved the worked examples yourself.