#384
Shuffle an Array
MediumArrayMathDesignRandomizedArrayRandomized Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n!) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses the Fisher-Yates shuffle algorithm, which efficiently shuffles the array in place. This method ensures that each element has an equal probability of ending up in any position, achieving the desired randomness without generating all permutations.
⚙️
Algorithm
4 steps- 1Step 1: Create a copy of the original array.
- 2Step 2: Iterate through the array from the last index to the first.
- 3Step 3: For each index, generate a random index from 0 to the current index.
- 4Step 4: Swap the current element with the element at the random index.
solution.py17 lines
1# Full working Python code
2import random
3
4class Solution:
5 def __init__(self, nums):
6 self.original = nums[:]
7 self.nums = nums
8
9 def reset(self):
10 return self.original
11
12 def shuffle(self):
13 shuffled = self.nums[:]
14 for i in range(len(shuffled) - 1, 0, -1):
15 j = random.randint(0, i)
16 shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
17 return shuffledℹ
Complexity note: The Fisher-Yates shuffle runs in linear time O(n) because it processes each element once, and uses O(n) space for the copy of the array.
- 1The Fisher-Yates algorithm is efficient for shuffling arrays.
- 2Randomness can be achieved without generating all permutations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.