Shuffle an Array Problem
Problem
Given an integer array nums
, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Implement the Solution
class:
Solution(int[] nums)
Initializes the object with the integer arraynums
.int[] reset()
Resets the array to its original configuration and returns it.int[] shuffle()
Returns a random shuffling of the array.
Example 1:
|
|
Examples
Solution
Method 1 - Using Fisher Yates Shuffle
We have seen Fisher-Yates Shuffle. Now, we can use it here.
Code:
|
|
Method 2 – Reservoir Sampling
Intuition
Reservoir sampling is a technique for randomly selecting k items from a stream of unknown size, ensuring each item has equal probability. For shuffling, we can use a similar idea: for each position, pick a random element from the remaining pool and swap. This is essentially the Fisher-Yates shuffle, but the term ‘reservoir sampling’ is sometimes used for the streaming version.
Approach
- Initialization:
- Store the original array for reset operations.
- Reset:
- Return the array to its original configuration.
- Shuffle (Reservoir Sampling):
- For each index, pick a random index from the current position to the end and swap the elements.
- This is equivalent to Fisher-Yates, but can be adapted for streaming data.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the length of the array. Each shuffle and reset operation is linear. - 🧺 Space complexity:
O(n)
, for storing the original and working arrays.