Shuffle the Array(#1470)

Category: Array, Foundation

๐Ÿงฉ Problem Statement

You're given an 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] In simpler terms, you're interleaving the first half and the second half of the array.

๐Ÿ“š Examples

Input: [1,1,2,2]

Output: [1,2,1,2]

Explanation: First half is [1,1], second half is [2,2]. Interleave them: [1,2,1,2].

๐Ÿง  Approach

โ€ข Simple Looping Strategy

โ€ข Create an empty array `ans = []`

โ€ข Loop from `i = 0` to `i < n`

โ€ข In each iteration, push `nums[i]` and `nums[i + n]` into `ans`

โ€ข Return the `ans` array

We're accessing elements from the first and second halves in a single loop.

๐Ÿ’ป Code

var shuffle = function(nums, n) {
  let ans = [];
  for (let i = 0; i < n; i++) {
    ans.push(nums[i]);
    ans.push(nums[i + n]);
  }
  return ans;
};

๐Ÿ“ˆ Complexity

Time: O(n)

Space: O(n)

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources