How I solved LeetCode Challenge, Shuffle the Array!
Hi Everyone,
Today I will be going over how I solved LeetCode Challenge, Shuffle the Array, using JavaScript.
Objective: Given the array nums
consisting of 2n
elements in the form [x1,x2,...,xn,y1,y2,...,yn]
.
Return the array in the form [x1,y1,x2,y2,...,xn,yn]
.
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
This challenge was an easy level challenge. I basically needed to make sure the elements are sorted in the appropriate order. If given [2,5,1,3,4,7] and n = 3, then I know I need to think of the array as the following [x¹,x²,x³,y¹,y²,y³].
I use a for loop and create and x and y variable. I want variable y set to n and x set to zero. It should increment as follows:
x=2 and y=3
x=5 and y=4
x=1 and y = 7
This is exactly how my new array should be sorted. I created a variable called shuffledArray and push my x and y each time it increments into the new array.
After the for loop completes I return the new array.
It passed all test!
Here is the final code:
var shuffle = function(nums, n) {
let shuffledArray = [];
for(let x=0, y=n; x < nums.length, y < nums.length; x++, y++){
shuffledArray.push(nums[x],nums[y])
}
return shuffledArray;
};
Runtime: 80 ms, faster than 95.41% of JavaScript online submissions for Shuffle the Array.
Memory Usage: 41.5 MB, less than 5.01% of JavaScript online submissions for Shuffle the Array.