Python 0384.py
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def reset(self) -> List[int]:
return self.nums
def shuffle(self) -> List[int]:
# see C++ std::random_shuffle
result = self.nums.copy()
size = len(result)
for i in range(size - 1, 0, -1):
pos = randint(0, i)
result[i], result[pos] = result[pos], result[i]
return result
Difficulty
and has an acceptance rate of about 60% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Design
- Math
- Randomized
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided module defines a Solution class that encapsulates a sequence of integers and offers two operations: restoring the original ordering and producing a random permutation of the stored values. The design isolates the original data from the mutable shuffle result, guaranteeing that repeated calls to reset always yield the initial configuration while each invocation of shuffle generates an independent random ordering.
Key Components
Constructor
The __init__ method receives a list of integers and assigns it to an instance attribute. By keeping a direct reference to the supplied list, the class preserves the exact sequence that will be used as the baseline for subsequent resets.
def __init__(self, nums: List[int]):
self.nums = nums
Reset Method
reset simply returns the stored original list. Because the attribute holds the untouched input, callers receive the exact same object that was supplied at construction time, ensuring deterministic restoration without any additional computation.
def reset(self) -> List[int]:
return self.nums
Shuffle Method
The shuffle routine implements the Fisher-Yates algorithm, a classic method for generating a uniform random permutation. The steps are:
- Create a shallow copy of the original list so that the source data remains unchanged.
- Determine the length of the copy.
- Iterate from the last index down to the second element, selecting a random position within the current prefix and swapping the elements at the two indices.
def shuffle(self) -> List[int]:
# see C++ std::random_shuffle
result = self.nums.copy()
size = len(result)
for i in range(size - 1, 0, -1):
pos = randint(0, i)
result[i], result[pos] = result[pos], result[i]
return result
Edge Cases Handled
When the input list is empty, size becomes zero, the loop range evaluates to an empty sequence, and the method returns a fresh empty list-behaving correctly without raising errors.
If the list contains a single element, size equals one, the loop again has no iterations, and the single-element copy is returned unchanged, which is the only valid permutation.
Repeated values in the list do not affect the algorithm; each position is treated independently, and swapping identical elements is harmless, preserving the uniform distribution of permutations even when duplicates exist.
Performance Optimizations
The implementation avoids unnecessary allocations by working on a shallow copy rather than constructing a new list element by element. Swapping is performed in place within the copied list, eliminating the need for auxiliary data structures.
Iterating backward from the end of the list reduces the range of the random index (randint(0, i)) as the algorithm progresses, which minimizes the number of possible positions for each swap and aligns with the optimal form of Fisher-Yates.
Using Pythonβs built-in randint for random selection leverages the underlying C implementation, providing fast generation of uniformly distributed integers within the required bounds.
Overall, the code delivers a concise, efficient solution for resetting and shuffling an integer array while correctly handling empty, singleton, and duplicate-containing inputs.
ELI5 - Simplified Explanation
Imagine you have a box full of numbered blocks. The very first part of this code is like a special labelmaker that remembers exactly how those blocks are arranged at the beginning. It keeps a secret notebook where it writes down the original order so those blocks can always be put back in their starting places whenever anyone wants to start over.
The second part is like a magical game for mixing up the blocks. It takes all the blocks out and puts them into a new pile. Then it goes through the pile one by one, picking two blocks and swapping their spots. It keeps doing this until every single block has been moved to a totally new and random location. By the time it finishes, the blocks are in a completely different order than how they started, just like shuffling a deck of cards so the game can be fresh and exciting every time.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | JS | Java | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 470: Implement Rand10() Using Rand7()
Solved On The Same Day
- problem 205: Isomorphic Strings
- problem 905: Sort Array By Parity
- problem 922: Sort Array By Parity II
- problem 2423: Remove Letter To Equalize Frequency
- problem 18: 4Sum
- problem 80: Remove Duplicates from Sorted Array II
- problem 92: Reverse Linked List II
- problem 93: Restore IP Addresses
- problem 1143: Longest Common Subsequence
- problem 1615: Maximal Network Rank
- problem 32: Longest Valid Parentheses
- problem 149: Max Points on a Line
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality