Leetcode 384: Shuffle an Array

grid47
grid47
Exploring patterns and algorithms
Sep 29, 2024 5 min read

A glowing array where elements shuffle into new positions, gently highlighting the change.
Solution to LeetCode 384: Shuffle an Array Problem

You are 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.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array nums.
Example: nums = [1, 2, 3]
Constraints:
• 1 <= nums.length <= 50
• -10^6 <= nums[i] <= 10^6
• All elements of nums are unique.
Output: The output consists of the array after applying the shuffle or reset method.
Example: Output: [3, 1, 2] after shuffle, [1, 2, 3] after reset
Constraints:
• The result of shuffle should be a random permutation of the array.
• The result of reset should return the array in its original configuration.
Goal: The goal is to implement a random shuffle that gives each permutation an equal probability.
Steps:
• Save the original configuration of the array.
• Use the Fisher-Yates (or Knuth) algorithm to shuffle the array randomly.
• On calling reset, return the original configuration.
• On calling shuffle, return a new randomly shuffled version of the array.
Goal: Ensure that the solution is efficient and works within the problem's constraints.
Steps:
• The solution should handle up to 10^4 shuffle and reset operations efficiently.
Assumptions:
• The input array is non-empty and has unique elements.
Input: Input: [1, 2, 3]
Explanation: The shuffle operation should return a random permutation of [1, 2, 3] such as [3, 1, 2]. The reset operation should return the array to its original form [1, 2, 3].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus