Problem 384

Abstract / Summary

Implement a function that can shuffle and reset an integer array to its original order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
17 lines | 452 bytes | submitted August 18, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • Math
  • Randomized
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. Create a shallow copy of the original list so that the source data remains unchanged.
  2. Determine the length of the copy.
  3. 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.00 | σ = 1.15

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
43 links | 27 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

4 easy 6 medium 2 hard
13 solutions   August 18, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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