Friday, January 8, 2021

Shuffle an Array

Problem: Given an integer array nums, design an algorithm to randomly shuffle the array.

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.


Approach: We can maintain two arrays in the class. One is original and second is shuffle. For shuffling the array, for every element of array, we can generate a random index and swap the current element with the random index.

Rest of the operations are straight forward.


Implementation in C#:

public class Solution 

{

    public Solution(int[] nums) 

   {

        this.original = nums;

        this.copy = (int[])nums.Clone();

    }

    

    public int[] Reset() 

   {

        return this.original;

    }

    

    public int[] Shuffle() 

    {      

        var random = new Random();  

        for (int i = 0; i <this.copy.Length; ++i)

        {

            int randomIndex = random.Next() % this.nums.Length;

            int temp = copy[i];

            copy[i] = copy[randomIndex];

            copy[randomIndex] = temp;

        }

        return copy;

    }

    

    private int[] original;

    private int[] copy;

}


Complexity: Shuffle - O(n), Reset - O(1)

No comments:

Post a Comment