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)