Shuffle an Array — LeetCode 384 Python Solution
- Problem
- #384
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["Solution", "shuffle", "reset", "shuffle"]
- Output
- [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
- Explanation
- Solution solution = new Solution([1, 2, 3]);
Python solution
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
self.original = nums.copy()
def reset(self) -> List[int]:
self.nums = self.original.copy()
return self.nums
def shuffle(self) -> List[int]:
for i in range(len(self.nums)):
j = random.randrange(i, len(self.nums))
self.nums[i], self.nums[j] = self.nums[j], self.nums[i]
return self.nums
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 384. Shuffle an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 384. Shuffle an Array?
- LeetCode 384. Shuffle an Array is rated Medium on LeetCode.
- What topics does LeetCode 384. Shuffle an Array cover?
- LeetCode 384. Shuffle an Array is tagged Design, Array, Math and Randomized on LeetCode.