384. Shuffle an Array
Medium ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Math & Geometry
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryDesign a class that stores an integer array and supports two operations: returning the array to its original order, and producing a uniformly random permutation of the array where every arrangement is equally likely.
Approach
- Store a copy of the original array at construction time so
reset()can return it in O(n). - Use the Fisher-Yates (Knuth) shuffle for
shuffle(): iterate indexifrom 0 to n-1, pick a random indexjin[i, n-1], and swap elements atiandj. - Each of the n! permutations is produced with equal probability because at step
ithere are exactlyn-iremaining positions to choose from, and the choices are independent. - Use a seeded Mersenne Twister (
mt19937) withstd::uniform_int_distributionfor high-quality, unbiased randomness.
#include <vector>
#include <random>
using namespace std;
class Solution {
vector<int> original; // immutable reference copy
mt19937 rng{random_device{}()}; // seeded Mersenne Twister
public:
Solution(vector<int>& nums) : original(nums) {}
// Return the array to its original configuration.
vector<int> reset() {
return original;
}
// Return a uniformly random permutation via Fisher-Yates shuffle.
vector<int> shuffle() {
vector<int> arr = original;
int n = arr.size();
for (int i = 0; i < n; ++i) {
// Pick a random index in [i, n-1] and swap into position i.
uniform_int_distribution<int> dist(i, n - 1);
swap(arr[i], arr[dist(rng)]);
}
return arr;
}
};
/**
* 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();
*/ Time O(n) per call — reset copies n elements; shuffle performs n swaps Space O(n) — one stored original copy plus one working copy returned per shuffle call
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
private:
mt19937 gen{random_device{}()};
vector<int> original;
int n;
public:
Solution(vector<int>& nums): original(nums), n(nums.size()) {}
vector<int> reset() {
return original;
}
vector<int> shuffle() {
vector<int> res=original;
for(int i=0; i<n; ++i){
uniform_int_distribution<int> dist(i, n-1);
swap(res[i], res[dist(gen)]);
}
return res;
}
};
/**
* 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();
*/ My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground C++
Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.
C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.