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 array nums.
  • 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 reset and shuffle

Visualization

Tap to expand
Shuffle an Array: Random Permutation GeneratorOriginal Array123🎲 Fisher-Yates ShuffleShuffled Result312Key Operations:• Initialize with original array• shuffle(): Random permutation• reset(): Restore original• All permutations equally likely• Time: O(n), Space: O(1)• Mathematically proven fairnessEvery arrangement has probability 1/n!
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
Asked in
Google 15 Facebook 12 Microsoft 10 Amazon 8
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen