Skip to content

Practice Shuffle an Array

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#384
LeetCode Problem

Shuffle an Array

Problem Statement

Solution(nums) stores an array of distinct integers. reset() returns its original ordering. shuffle() returns a permutation, with every possible permutation equally likely. Practice approach: Keep an untouched copy for reset. Apply Fisher-Yates to a working copy: at position i, swap with a uniformly chosen position from i through the last index. Restricting the random range as it shrinks makes each permutation equally likely. Randomly sorting by a comparator does not provide the same guarantee. Test that reset still works after multiple shuffles.

Source: Shuffle an Array on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["Solution","shuffle","reset","shuffle"]
[[[4,7,9]],[],[],[]]
Output
[null,[7,9,4],[4,7,9],[9,4,7]]
Explanation

The two shown permutations are possible outcomes; each of the six permutations must be equally likely. reset always returns [4,7,9].

Constraints

1 <= nums.length <= 50
-10^6 <= nums[i] <= 10^6
Array values are distinct.
At most 10^4 total reset and shuffle calls.

Related LeetCode Problems

Practice more problems similar to Shuffle an Array.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.