384. Shuffle an Array
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to design a class that can manage an array of integers. This class must support two main operations: shuffling the array randomly and resetting it to its initial state. The most critical requirement is that the shuffling process must ensure that all possible permutations of the array are equally likely. This points towards using a standard, statistically unbiased shuffling algorithm.
Solution
Shuffle an Array in Python
import random
class Solution:
def __init__(self, nums: List[int]):
# Store a copy of the original list.
self.original = list(nums)
def reset(self) -> List[int]:
# Resets the array to its original configuration and returns it.
# Return a copy to protect the internal state.
return list(self.original)
def shuffle(self) -> List[int]:
# Create a copy to shuffle, keeping the original intact.
shuffled = list(self.original)
n = len(shuffled)
# Implement the Fisher-Yates shuffle algorithm.
# Iterate from the last element down to the second.
for i in range(n - 1, 0, -1):
# Pick a random index j from 0 to i inclusive.
j = random.randint(0, i)
# Swap elements at indices i and j.
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
return shuffled
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
Shuffle an Array in Java
import java.util.Random;
class Solution {
private int[] original;
private Random rand;
public Solution(int[] nums) {
// Store a clone of the original array to prevent aliasing issues.
this.original = nums.clone();
this.rand = new Random();
}
public int[] reset() {
// Resets the array to its original configuration and returns it.
// We return a clone to prevent the caller from modifying the internal original array.
return this.original.clone();
}
public int[] shuffle() {
// Create a copy to shuffle, leaving the original array intact.
int[] shuffled = this.original.clone();
int n = shuffled.length;
// Implement the Fisher-Yates shuffle algorithm.
// Iterate from the last element to the second.
for (int i = n - 1; i > 0; i--) {
// Generate a random index 'j' from 0 to i (inclusive).
// rand.nextInt(i + 1) generates an int in [0, i].
int j = rand.nextInt(i + 1);
// Swap the elements at indices i and j.
int temp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = temp;
}
return shuffled;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/
Shuffle an Array in C++
class Solution {
private:
vector<int> original;
public:
Solution(vector<int>& nums) {
// Store the original configuration of the array.
// The vector's copy constructor handles creating a deep copy.
this->original = nums;
}
vector<int> reset() {
// Return the original array. In C++, returning a vector by value
// creates a copy, so the internal state is protected.
return this->original;
}
vector<int> shuffle() {
// Create a copy of the original array to shuffle.
vector<int> shuffled = this->original;
int n = shuffled.size();
// Implement the Fisher-Yates shuffle algorithm.
// Iterate from the last element to the second.
for (int i = n - 1; i > 0; --i) {
// Generate a random index 'j' from 0 to i (inclusive).
// rand() % (i + 1) gives a uniform random number in that range.
int j = rand() % (i + 1);
// Swap the elements at indices i and j.
swap(shuffled[i], shuffled[j]);
}
return shuffled;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* vector<int> param_1 = obj->reset();
* vector<int> param_2 = obj->shuffle();
*/
Shuffle an Array in TypeScript
class Solution {
private original: number[];
constructor(nums: number[]) {
// Store a copy of the original array.
this.original = nums.slice();
}
reset(): number[] {
// Resets the array to its original configuration and returns it.
// Return a copy to protect the internal state.
return this.original.slice();
}
shuffle(): number[] {
// Create a copy to shuffle, keeping the original intact.
const shuffled = this.original.slice();
const n = shuffled.length;
// Implement the Fisher-Yates shuffle algorithm.
// Iterate from the last element down to the second.
for (let i = n - 1; i > 0; i--) {
// Generate a random index 'j' from 0 to i (inclusive).
// Math.random() returns a float in [0, 1).
// Math.floor(Math.random() * (i + 1)) gives an integer in [0, i].
const j = Math.floor(Math.random() * (i + 1));
// Swap elements at indices i and j using destructuring assignment.
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
}
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.