leetcode 1470. Shuffle the Array

Posted on

This problem cant be looked at as such

  • The array nums is made of two arrays joined together
    • nums is [1,2,3,4]
  • separate the two array
    • array x is [1,2]
    • array y is [3,4]
  • recombine the arrays such that the new array is made in the following manner
    • x[0],y[0],x[1],y[1]
  • the result will be [1,3,2,4]
var shuffle = function(nums, n) {
    // the array nums can be divided into two subarrays
    // the value n is the length of each subarray
    //
    // To make this a one pass solution create two pointers
    //   one to the start of the first subarray
    //   the other to the start of the second subarray
    let p1 = 0
    let p2 = n  //conveniently n is the index pointer2 should be at
    const result = []
    while(p1<n){
        result.push(nums[p1])
        result.push(nums[p2])
        p1++
        p2++
    }
    return result
};
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s