Skip to main content
Back to problems
#384
Medium Algorithms

Shuffle an array

Array Math Design Randomized
59.6% acceptance
Jan 12, 2026
1430
946
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. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling of the array.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
struct Solution {
  original: Vec<i32>,
  array: Vec<i32>,
}

impl Solution {
  fn new(nums: Vec<i32>) -> Self {
    Solution {
      array: nums.clone(),
      original: nums,
    }
  }
  
  fn reset(&mut self) -> Vec<i32> {
    self.array = self.original.clone();
    self.original.clone()
  }
  
  fn shuffle(&mut self) -> Vec<i32> {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hash, Hasher};
    
    let n = self.array.len();
    
    // Fisher-Yates shuffle algorithm
    for i in (1..n).rev() {
      // Generate random index from 0 to i (inclusive)
      let state = RandomState::new();
      let mut hasher = state.build_hasher();
      (i as u64).hash(&mut hasher);
      let hash = hasher.finish();
      let j = (hash as usize) % (i + 1);
      
      // Swap elements at positions i and j
      self.array.swap(i, j);
    }
    
    self.array.clone()
  }
}