#1470

Shuffle the Array

Easy Index arithmetic

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

The array holds x1..xn followed by y1..yn. Return it interleaved as x1, y1, x2, y2, ...

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: take the first half (x's) and the second half (y's) and zip them together: x1, y1, x2, y2…

Why this works: x_i lives at index i and y_i at index i + n; in the answer they go to 2i and 2i + 1.

Example: nums = [2, 5, 1, 3, 4, 7], n = 3

x = [2, 5, 1], y = [3, 4, 7]i=0 → ans[0]=2, ans[1]=3i=1 → ans[2]=5, ans[3]=4i=2 → ans[4]=1, ans[5]=7ans = [2, 3, 5, 4, 1, 7]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Looping i up to 2n instead of n, which reads past the first half.