Shuffle the Array
Problem
Given the array nums of size 2n, return the array in the form [x1,y1,x2,y2,…,xn,yn].
Input
nums = [2,5,1,3,4,7], n = 3Output
[2,3,5,4,1,7]x = [2,5,1], y = [3,4,7] → interleave.
def shuffle(nums, n):
out = []
for i in range(n):
out.append(nums[i]); out.append(nums[n + i])
return out
function shuffle(nums, n) {
const out = [];
for (let i = 0; i < n; i++) { out.push(nums[i]); out.push(nums[n + i]); }
return out;
}
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] r = new int[2 * n];
for (int i = 0; i < n; i++) { r[2*i] = nums[i]; r[2*i+1] = nums[n+i]; }
return r;
}
}
vector shuffle(vector& nums, int n) {
vector r(2 * n);
for (int i = 0; i < n; i++) { r[2*i] = nums[i]; r[2*i+1] = nums[n+i]; }
return r;
}
Explanation
The array secretly holds two halves: the first n values are the x group and the last n values are the y group. We need to weave them together as x1, y1, x2, y2, ….
The fix is a simple loop over i from 0 to n-1. For each i we grab one item from the front half, nums[i], and its partner from the back half, nums[n + i], and append them next to each other.
Because element i of the first half always pairs with element i of the second half (which sits at offset n + i), one pass produces the full interleaved result in order.
Example: nums = [2,5,1,3,4,7], n = 3. The halves are x = [2,5,1] and y = [3,4,7]. We output 2,3 then 5,4 then 1,7, giving [2,3,5,4,1,7].