Shuffle the Array

(#1470), Easy

Category: Array

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 after the loop ends.
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