Skip to content

384. Shuffle an Array

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  Solution(vector<int>& nums) : nums(std::move(nums)) {}

  /** Resets the array to its original configuration and return it. */
  vector<int> reset() {
    return nums;
  }

  /** Returns a random shuffling of the array. */
  vector<int> shuffle() {
    vector<int> A(nums);
    for (int i = A.size() - 1; i > 0; --i) {
      const int j = rand() % (i + 1);
      swap(A[i], A[j]);
    }
    return A;
  }

 private:
  vector<int> nums;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public Solution(int[] nums) {
    this.nums = nums;
  }

  /** Resets the array to its original configuration and return it. */
  public int[] reset() {
    return nums;
  }

  /** Returns a random shuffling of the array. */
  public int[] shuffle() {
    int[] A = nums.clone();
    for (int i = A.length - 1; i > 0; --i) {
      final int j = rand.nextInt(i + 1);
      swap(A, i, j);
    }
    return A;
  }

  private int[] nums;
  private Random rand = new Random();

  private void swap(int[] A, int i, int j) {
    final int temp = A[i];
    A[i] = A[j];
    A[j] = temp;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def __init__(self, nums: list[int]):
    self.nums = nums

  def reset(self) -> list[int]:
    """
    Resets the array to its original configuration and return it.
    """
    return self.nums

  def shuffle(self) -> list[int]:
    """
    Returns a random shuffling of the array.
    """
    A = self.nums.copy()
    for i in range(len(A) - 1, 0, -1):
      j = random.randint(0, i)
      A[i], A[j] = A[j], A[i]
    return A