Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #384: Shuffle an Array

In this guide, we solve Leetcode #384 Shuffle an Array in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Design, Array, Math, Randomized

Intuition

There is a mathematical invariant or formula that directly leads to the result.

Using math avoids unnecessary loops and reduces complexity.

Approach

Derive the formula or update rule, then compute the answer directly.

Handle edge cases like overflow or zero carefully.

Steps:

  • Identify the math relationship.
  • Compute the result with a loop or formula.
  • Handle edge cases.

Example

Input ["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []] Output [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] Explanation Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]

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

The time complexity is O(n) or O(1). The space complexity is O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy