#1470 Shuffle the Array
the problem
In plain words
nums holds 2n numbers: first x1…xn, then y1…yn. Return them interleaved: [x1, y1, x2, y2, …, xn, yn].
in nums = [2,5,1,3,4,7], n = 3
out [2,3,5,4,1,7]
x = 2,5,1 and y = 3,4,7, taken in turns.
in nums = [1,2,3,4,4,3,2,1], n = 4
out [1,4,2,3,3,2,4,1]
in nums = [1,1,2,2], n = 2
out [1,2,1,2]
- 1 ≤ n ≤ 500
- nums.length == 2n
- 1 ≤ nums[i] ≤ 1000
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternSimulation
Pure index arithmetic: x(i+1) is nums[i] and goes to slot 2i; its partner y(i+1) is nums[i + n] and goes to slot 2i + 1.
solutions
From brute force to optimal
Cut the x half and the y half into their own arrays, then take one from each in turn.
- xs = copyOfRange(nums, 0, n), ys = copyOfRange(nums, n, 2n).
- result[2i] = xs[i], result[2i + 1] = ys[i].
Two copies plus one merge pass.
The two half-copies, on top of the answer.
class Solution { public int[] shuffle(int[] nums, int n) { int[] xs = Arrays.copyOfRange(nums, 0, n); // x1..xn (a copy) int[] ys = Arrays.copyOfRange(nums, n, 2 * n); // y1..yn (another copy) int[] result = new int[2 * n]; for (int i = 0; i < n; i++) { result[2 * i] = xs[i]; result[2 * i + 1] = ys[i]; } return result; }}Read straight from nums: x(i+1) = nums[i], y(i+1) = nums[i + n].
- result = new int[2n].
- For i in 0..n−1: result[2i] = nums[i], result[2i + 1] = nums[i + n].
One pass, two writes per step.
Only the answer array.
class Solution { public int[] shuffle(int[] nums, int n) { int[] result = new int[2 * n]; for (int i = 0; i < n; i++) { result[2 * i] = nums[i]; // x(i+1) lands on an even index result[2 * i + 1] = nums[i + n]; // its partner y(i+1) sits n slots later } return result; }}in the room
How to say it in the interview
talk track
- Write the mapping for n = 3 on paper first: index 0 → 0, 3 → 1, 1 → 2, 4 → 3, …
- Then the loop writes itself — say the two formulas out loud.
traps
- Looping i up to 2n and reading
nums[i + n]→ out of bounds. - Mixing up
n(half the length) withnums.length(2n).
what they ask next
Follow-ups
Can you do it in place with O(1) extra space?
Yes, because values ≤ 1000 < 2¹⁰: pack each y into the high bits of its x's slot, then unpack from the back so nothing unread is overwritten. A neat trick, rarely asked.
before you submit
Edge cases to test
- n = 1: [9, 4] stays [9, 4].
- Duplicates don't matter — only positions do.
practise next
Similar problems
- #1929Concatenation of ArrayEasyin Java Arrays & Strings
- #189Rotate ArrayMediumin Arrays & Strings