Shuffle an Array - Problem

๐ŸŽฒ Shuffle an Array - Random Permutation Generator

You are given an integer array nums and need to design an algorithm that can randomly shuffle the array while ensuring that all permutations are equally likely.

Challenge: Create a Solution class that maintains the original array and provides two key operations:

  • Reset: Restore the array to its original configuration
  • Shuffle: Generate a truly random permutation where each arrangement has equal probability

Key Requirements:

  • Each of the n! possible permutations should have probability 1/n!
  • The shuffle should be unbiased - no arrangement should be favored over others
  • Must be efficient for repeated shuffle operations

Example: For array [1,2,3], each of the 6 permutations [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] should appear with equal likelihood over many shuffles.

Input & Output

example_1.py โ€” Basic Usage
$ Input: nums = [1, 2, 3] solution = Solution(nums) solution.shuffle() solution.reset() solution.shuffle()
โ€บ Output: [3, 1, 2] (example) [1, 2, 3] [1, 3, 2] (example)
๐Ÿ’ก Note: The shuffle() method returns a random permutation. Each call produces a potentially different result. reset() always returns the original array [1,2,3].
example_2.py โ€” Single Element
$ Input: nums = [1] solution = Solution(nums) solution.shuffle() solution.reset()
โ€บ Output: [1] [1]
๐Ÿ’ก Note: With only one element, there's only one possible permutation. Both shuffle() and reset() return [1].
example_3.py โ€” Larger Array
$ Input: nums = [1, 2, 3, 4, 5] solution = Solution(nums) solution.shuffle() solution.reset()
โ€บ Output: [4, 1, 5, 2, 3] (example) [1, 2, 3, 4, 5]
๐Ÿ’ก Note: With 5 elements, there are 5! = 120 possible permutations. The Fisher-Yates algorithm ensures each has equal 1/120 probability.

Visualization

Tap to expand
๐ŸŽด Fisher-Yates Shuffle: The Perfect Card Shuffle๐ŸŽฏ The Challenge: Equal ProbabilityFor array [A, B, C, D], we need each of the 4! = 24 permutations to have exactly 1/24 = 4.17% chanceFisher-Yates guarantees this by making exactly n random decisions, one for each positionTime: O(n) | Space: O(1) extra | Perfectly uniform distribution โœ…Step-by-Step Process:Initial: [A, B, C, D]ABCDโ† Start here (i=3)Step 1: i=3, j=random(0,3)=1 โ†’ Swap D with BADCBStep 2: i=2, j=random(0,2)=0 โ†’ Swap C with ACDABStep 3: i=1, j=random(0,1)=1 โ†’ Swap D with itselfCDABโœ“ Done!๐Ÿงฎ Mathematical ProofWhy does this work?โ€ข Position 3: Element has 1/4 chance to stayโ€ข Position 2: Element has 1/3 chance to stayโ€ข Position 1: Element has 1/2 chance to stayโ€ข Position 0: Element has 1/1 chance to stayTotal arrangements:4 ร— 3 ร— 2 ร— 1 = 24 = 4!Each permutation probability:(1/4) ร— (1/3) ร— (1/2) ร— (1/1) = 1/24 โœ“๐Ÿš€ Performance Benefits:โ€ข No memory for storing permutationsโ€ข Linear time complexityโ€ข Perfect uniform distribution๐Ÿ’ก Key InsightInstead of generating all n! permutations and picking randomly (expensive), we make n random decisionssequentially. Each decision has exactly the right probability to ensure uniform distribution!
Understanding the Visualization
1
Start from End
Begin with the last element in the array. This represents the bottom card in our deck.
2
Random Selection
Generate a random index from 0 to current position (inclusive). This chooses which card to swap with.
3
Swap Elements
Exchange the current element with the randomly selected element. This ensures randomness.
4
Move Backward
Move to the previous position and repeat. Each position gets exactly one chance to be swapped.
5
Perfect Shuffle
After processing all positions, every permutation has exactly 1/n! probability.
Key Takeaway
๐ŸŽฏ Key Insight: The Fisher-Yates shuffle achieves perfect randomness by making exactly n sequential random decisions, ensuring each of the n! permutations has equal probability 1/n! while using only O(n) time and O(1) extra space.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array, each swap is O(1)

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Only need to store original array copy for reset functionality

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 50
  • -106 โ‰ค nums[i] โ‰ค 106
  • At most 104 calls will be made to reset and shuffle combined
  • All elements in nums are unique
Asked in
Google 42 Microsoft 38 Amazon 31 Facebook 24
73.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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