Shuffle the Array - Problem

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
💡 Note: First half is [2,5,1] and second half is [3,4,7]. Alternate: 2,3,5,4,1,7
Example 2 — Smaller Array
$ Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
💡 Note: First half [1,2,3,4], second half [4,3,2,1]. Result: [1,4,2,3,3,2,4,1]
Example 3 — Minimum Size
$ Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
💡 Note: First half [1,1], second half [2,2]. Alternate: [1,2,1,2]

Constraints

  • 1 ≤ n ≤ 500
  • nums.length == 2n
  • 1 ≤ nums[i] ≤ 103

Visualization

Tap to expand
Shuffle the Array - Direct Index Mapping INPUT nums = [2,5,1,3,4,7], n = 3 Original Array (2n = 6 elements) X section (0 to n-1) Y section (n to 2n-1) 2 x1 5 x2 1 x3 3 y1 4 y2 7 y3 i=0 i=1 i=2 i=3 i=4 i=5 Goal: Interleave X and Y [x1,y1,x2,y2,x3,y3] Index Mapping Formula: result[2*i] = nums[i] result[2*i+1] = nums[n+i] ALGORITHM STEPS 1 Initialize result array Create empty array of size 2n 2 Loop i from 0 to n-1 Iterate through first half 3 Map X elements result[2*i] = nums[i] 4 Map Y elements result[2*i+1] = nums[n+i] Index Mapping Table i=0: result[0]=2, result[1]=3 i=1: result[2]=5, result[3]=4 i=2: result[4]=1, result[5]=7 Time: O(n) | Space: O(n) FINAL RESULT Shuffled Array: 2 3 5 4 1 7 x1 y1 x2 y2 x3 y3 [2, 3, 5, 4, 1, 7] OK - Pattern Verified! Interleaved Pattern: X and Y elements alternate Blue(X) - Green(Y) - Blue(X) ... Pairs: (2,3), (5,4), (1,7) SUCCESS Key Insight: The direct index mapping approach uses a simple mathematical formula to place elements at their correct positions in O(1) time per element. Elements from index i go to position 2*i, and elements from index n+i go to position 2*i+1, creating the perfect interleaved pattern in a single pass. TutorialsPoint - Shuffle the Array | Direct Index Mapping Approach
Asked in
Amazon 15 Apple 12
180.0K Views
Medium Frequency
~15 min Avg. Time
3.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen