← Back to DSA Animator
Shuffle the Array LC #1470 Easy Array Basics
Problem

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].

Example 1
Input: nums = [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: [2,3,5,4,1,7].
Constraints: 1≤n≤500  |  nums.length==2n  |  1≤nums[i]≤10³
Try Examples
Custom:
Approach
Interleave Two Halves
The input has x-values at indices 0..n-1 and y-values at n..2n-1. For each i: place nums[i] (x) then nums[i+n] (y) into the result. One pass, O(n) space.
Array Visualization
Variables
Index i
x=nums[i]
y=nums[i+n]
write pos
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Get n = nums.length / 2; create result of size 2n
2
For i = 0..n-1: pick x=nums[i], y=nums[i+n]
3
Place x at result[2i], y at result[2i+1]
4
Return the interleaved result array
Time
O(n)
Space
O(n)
Why It Works

The x-values are in the first half (indices 0..n-1) and y-values in the second half (n..2n-1). For each pair index i, we pick nums[i] and nums[i+n] and write them consecutively. The write position is always 2i and 2i+1.