LeetCode – Shuffle the Array

Link: https://leetcode.com/problems/shuffle-the-array/

Solution:

  • iterate n times (half size of the array)
  • each iteration will add a pair (x1, y1) to the output array. x1 = nums[i] and y1 = nums[i + n]
/**
 * @param {number[]} nums
 * @param {number} n
 * @return {number[]}
 */
var shuffle = function(nums, n) {
    const output = new Array(2*n);

    for(var i = 0; i < n; i++)
    {
        output[i * 2] = nums[i];
        output[i * 2 + 1] = nums[i + n];
    }

    return output;
};

Time Complexity: O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *