Build a class Solution that is created from an array of distinct integers, nums, and has two methods. shuffle() returns the numbers in a random order. reset() returns them in the order they were first given.
The shuffle must be fair: each of the n! possible orders has to come out with the same probability, every time shuffle() is called.
Example 1
Input: Solution([4, 7, 1, 9]), then shuffle(), reset(), shuffle() Output: any order such as [9, 4, 1, 7]; then [4, 7, 1, 9]; then any order Why: each of the 24 orders is equally likely; reset gives the start back
2 more examples and the constraints
Example 2
Input: Solution([5]), then shuffle(), reset() Output: [5]; then [5] Why: one number has only one order
Example 3
Input: Solution([-3, 8]), then shuffle(), shuffle(), reset() Output: [-3, 8] or [8, -3], each half the time, twice; then [-3, 8] Why: two numbers have two orders
Constraints
- 1 ≤ length of nums ≤ 50
- −1,000,000 ≤ nums[i] ≤ 1,000,000, and all values are different
- reset and shuffle are called at most 10,000 times in total
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Draw from a poolO(n²) per shuffle
- Fisher–Yates shuffleO(n) per shuffle
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for one shuffle of 50 numbers | Verdict |
|---|---|---|---|
| Draw from a pool | O(n²) | Passes; removals shift the list | |
| Fisher–Yates shuffle | O(n) | Best; one swap per slot |
n = length of nums. Both use O(n) extra space for the stored original.
Edge cases to test
- One number. The loop does nothing and the only order is returned.
- Reset after shuffles. Shuffle a copy, never the stored original, or reset will return a shuffled array.
- Calling reset first. It must return the original order even if shuffle was never called.
- Swapping with itself. j may equal i. That is how a number gets to stay where it is.
Common mistakes
- Choosing j from the whole array on every step, which makes some orders more likely than others.
- Shuffling the stored array in place and then returning it from reset.
- Using
random() * iinstead ofrandom() * (i + 1), so a slot can never keep its own number.
How to talk through it
- 1Clarify. Must all n! orders be equally likely? Does reset return the very first order? Are values distinct?
- 2Start with a hat. Draw a random remaining number each time: fair, but O(n²) because of removals.
- 3Remove the removals. Keep the remaining numbers in the front of the array and swap the pick into the back.
- 4Argue fairness. Slot n − 1 gets each number with chance 1/n, slot n − 2 each remaining one with 1/(n − 1), and so on: 1/n! per order.
- 5Test out loud. Shuffle [4, 7, 1, 9] with fixed picks, check it is a permutation, then check reset gives [4, 7, 1, 9].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?