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).

2 variations · 2 problems · 1 with animated walkthroughs

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

Randomized Algorithms
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;
    }
}

The variations

  1. 1Fisher-Yates shuffle

    Position i gets 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 so reset is a copy.

  2. 2More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Picking j from the whole array on every step: it looks random but some orders come up more often than others.
  • Picking j from [0, i - 1], which never leaves an item in place: also biased.
  • Shuffling the stored array itself, so reset returns the shuffled order.
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.