# LeetCode: Shuffle an Array Solution

Fisher–Yates shuffle

## Approach

Use Fisher–Yates shuffle algorithm

With every

i
from
0
to
N-1
(
N
is length of the array)

• get random integer
j
in range
[i, N-1]
• swap
array[i]
and
array[j]

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} nums3 */4var Solution = function (nums) {5  this.orignalNums = [...nums]6  this.nums = [...nums]7}8
9/**10 * Resets the array to its original configuration and return it.11 * @return {number[]}12 */13Solution.prototype.reset = function () {14  this.nums = [...this.orignalNums]15  return this.nums16}17
18/**19 * Returns a random shuffling of the array.20 * @return {number[]}21 */22Solution.prototype.shuffle = function () {23  for (let i = 0; i < this.nums.length; i++) {24    const j = getRandomInt(i, this.nums.length)25    ;[this.nums[i], this.nums[j]] = [this.nums[j], this.nums[i]]26  }27  return this.nums28}29
30function getRandomInt(min, max) {31  return Math.floor(Math.random() * (max - min) + min)32}33
34/**35 * Your Solution object will be instantiated and called as such:36 * var obj = new Solution(nums)37 * var param_1 = obj.reset()38 * var param_2 = obj.shuffle()39 */```

leetcode

array

math

## Next Post

LeetCode: Partition Array into Disjoint Intervals

Jul 22, 2021

Reasoning

Search Posts