Algo-Sim › Math & Geometry
Shuffle an Array
Medium · Math & Geometry · step through it in Java, Python and C++ on your own input
Fisher–Yates: for i from the back, swap a[i] with a uniform j ≤ i. Every one of the n! orderings is equally likely.
Problem
Given an integer array nums, design a class whose shuffle() returns a random permutation of the array in which every permutation is equally likely, and whose reset() returns the array in its original order.
Constraints
- 1 ≤ nums.length ≤ 50
- All values are unique
- At most 10⁴ calls in total
- Here a seed fixes the random draws so runs repeat
Edge cases to test
- One element
- Duplicate values
resetafter several shuffles
Follow-up questions
- Why is "swap each i with any j" biased?
- It has nⁿ equally likely runs, which isn’t divisible by n! for n > 2, so some orderings appear more often.
- How do you sample k items without replacement?
- Run Fisher–Yates for only k steps: O(k) time after the O(n) copy.
Solution
Java
class Solution {
private final int[] original;
private final Random rand = new Random();
public Solution(int[] nums) {
original = nums.clone();
}
public int[] reset() {
return original.clone();
}
// Fisher–Yates: fill positions from the back with a uniform pick of what is left.
public int[] shuffle() {
int[] a = original.clone();
for (int i = a.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
int t = a[i]; a[i] = a[j]; a[j] = t;
}
return a;
}
}Python
import random
class Solution:
def __init__(self, nums):
self.original = nums[:]
def reset(self):
return self.original[:]
# Fisher–Yates: fill positions from the back with a uniform pick of what is left.
def shuffle(self):
a = self.original[:]
for i in range(len(a) - 1, 0, -1):
j = random.randint(0, i)
a[i], a[j] = a[j], a[i]
return aC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
vector<int> original;
public:
Solution(vector<int> &nums) : original(nums) {}
vector<int> reset() { return original; }
// Fisher–Yates: fill positions from the back with a uniform pick of what is left.
vector<int> shuffle() {
vector<int> a = original;
for (int i = int(a.size()) - 1; i > 0; i--) {
int j = rand() % (i + 1);
swap(a[i], a[j]);
}
return a;
}
};
More Math & Geometry problems
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Multiply Strings (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)