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

1/**
2 * @param {number[]} nums
3 */
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.nums
16}
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.nums
28}
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 */

Comments

Loading comments...

Tags

leetcode

array

math

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Partition Array into Disjoint Intervals

Jul 22, 2021

Reasoning

Previous Post

HoningJS

Search Posts