Problem Description
Given an integer array nums, design an algorithm to randomly shuffle the array. Ensure that every permutation of the array is equally likely to be returned by the shuffle method. The class should also provide a reset function that returns the array to its original configuration.
Key Insights
- Use the Fisher-Yates (Knuth) shuffle algorithm to achieve an unbiased shuffle.
- Save the original configuration of the array to allow for a reset.
- The Fisher-Yates algorithm works by iterating over the array and swapping each element with another randomly chosen element.
Space and Time Complexity
Time Complexity: O(n) for both shuffling and resetting the array. Space Complexity: O(n) due to storing a copy of the original array.
Solution
We store a copy of the initial array to enable resetting. The shuffle method uses the Fisher-Yates algorithm. For each index i from the beginning to the end of the array, we choose a random index between i and the end of the array and swap the elements at indices i and the chosen index. This method ensures every permutation is equally likely.