Shuffle an Array - 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.
Input & Output
Example 1 — Basic Shuffle
$
Input:
nums = [1,2,3]
›
Output:
[3,1,2] (or any permutation)
💡 Note:
Initialize with [1,2,3], shuffle() returns a random permutation like [3,1,2], reset() returns [1,2,3], shuffle() returns another random arrangement
Example 2 — Single Element
$
Input:
nums = [1]
›
Output:
[1]
💡 Note:
Only one element, so shuffle() always returns [1], reset() returns [1]
Example 3 — Duplicate Values
$
Input:
nums = [1,1,2]
›
Output:
[2,1,1] (or any permutation)
💡 Note:
Even with duplicates, all permutations should be equally likely: [1,1,2], [1,2,1], [2,1,1]
Constraints
- 1 ≤ nums.length ≤ 50
- -106 ≤ nums[i] ≤ 106
- All the elements of nums are unique
-
At most 104 calls will be made to
resetandshuffle
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original array [1,2,3] to be shuffled
2
Process
Apply Fisher-Yates algorithm for random shuffling
3
Output
Any random permutation like [3,1,2]
Key Takeaway
🎯 Key Insight: Fisher-Yates shuffle ensures mathematical fairness with optimal O(n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code