Implement shuffle(), which returns a random permutation of the array with every permutation equally likely, and reset(), which returns the array in its original order.
Before you code
Swapping each position with a random position anywhere in the array looks reasonable. Count its equally likely outcomes for n = 3 and compare with the number of permutations.
Hints
- Keep a copy of the original for reset.
- For i from n − 1 down to 1, draw j uniformly from 0 to i, inclusive, and swap positions i and j.
- To test it, shuffle [1, 2, 3] a hundred thousand times and count each permutation: all six counts should be close to one sixth. Try the biased version too and see the difference.
Production & complexity notes
When solving Shuffle an array on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Randomized algorithms to reinforce the underlying pattern.
What it practices
Uniform shuffling and why it is uniform, from Randomized algorithms.