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 - Fisher-Yates Algorithm INPUT Original Array: nums 1 idx 0 2 idx 1 3 idx 2 Input Parameters nums = [1, 2, 3] Length: 3 elements Store copy for reset() original = [1, 2, 3] ALGORITHM STEPS 1 Start from end (i=2) Pick random j from [0,i] 1 2 3 i=2 2 Swap nums[i], nums[j] e.g., j=0: swap(3,1) 3 2 1 3 Decrement i (i=1) Repeat: j=0, swap(2,3) 2 3 1 i=1 4 Continue until i=0 Return shuffled array Time: O(n) | Space: O(n) FINAL RESULT Shuffled Array 3 idx 0 1 idx 1 2 idx 2 Output [3, 1, 2] All Possible Results: [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] Each has 1/6 probability OK - Uniform Random Key Insight: Fisher-Yates ensures each permutation has equal probability (1/n!). By iterating backwards and swapping with a random element from the remaining unshuffled portion, we guarantee uniformity. reset() restores original array | shuffle() creates random permutation in O(n) time TutorialsPoint - Shuffle an Array | Fisher-Yates Shuffle Algorithm
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