easy

Shuffle the Array

Interleave two halves of an array back into one sequence.

1. Define the problem

Shuffle the Array

Given the 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] . Walk one pointer through the first half (the x values) and another through the second half (the y values), building the interleaved result as you go.

Constraints

  • 1 ≤ n ≤ 500
  • nums.length == 2n
  • 1 ≤ numsi ≤ 103

Example

Inputnums = [2, 5, 1, 3, 4, 7], n = 3
Output[2, 3, 5, 4, 1, 7]

Explanation x = [2, 5, 1], y = [3, 4, 7], interleaved as [2, 3, 5, 4, 1, 7].

2. Visualize the solution

Interleave the first half with the second half

Interleave the first half with the second half
Statusinit

i=0: x[0]=2 (index 0), y[0]=3 (index 3). Append 2, then 3.

What happens in this step

i = 0, x[0] = nums[0] = 2, y[0] = nums[0+n]=nums[3] = 3
result = [2, 3]
Step 1 of 3

Steps to visualize

  1. Split nums into the first half (x values, indices 0 to n-1) and the second half (y values, indices n to 2n-1).
  2. For each position i from 0 to n-1, append xi then yi to the result.
  3. The result alternates one value from each half at a time.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Interleave the first half with the second half
Statusinit

i=0: x[0]=2 (index 0), y[0]=3 (index 3). Append 2, then 3.

What happens in this step

i = 0, x[0] = nums[0] = 2, y[0] = nums[0+n]=nums[3] = 3
result = [2, 3]
Step 1 of 3
4. Solution

Solution

solution.tsTypeScript
function shuffle(nums, n) {
  const result = [];

  for (let i = 0; i < n; i++) {
    result.push(nums[i]);
    result.push(nums[i + n]);
  }

  return result;
}
Time
O(n)
Space
O(n)
5. Test cases

Test cases

InputExpectedCovers
nums = [2, 5, 1, 3, 4, 7], n = 3[2, 3, 5, 4, 1, 7]example from the docstring
nums = [1, 2], n = 1[1, 2]smallest valid input, a single pair
nums = [4, 4, 4, 4], n = 2[4, 4, 4, 4]every value identical
nums = [1, 2, 3, 4, 4, 3, 2, 1], n = 4[1, 4, 2, 3, 3, 2, 4, 1]larger input with a palindromic pattern
nums = [1, 1, 2, 2], n = 2[1, 2, 1, 2]duplicate values across the two halves
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n = 5[1, 6, 2, 7, 3, 8, 4, 9, 5, 10]larger input to confirm interleaving scales