Shuffle the Array - Problem
Shuffle the Array is a fundamental array manipulation problem that tests your understanding of index mapping and pattern recognition.

You're given an array nums containing exactly 2n elements, structured as two equal halves: [x₁, x₂, ..., xₙ, y₁, y₂, ..., yₙ]. The first half contains the x-values and the second half contains the corresponding y-values.

Your task is to interleave these two halves to create a new array in the format: [x₁, y₁, x₂, y₂, ..., xₙ, yₙ].

Example: If nums = [2, 5, 1, 3, 4, 7] where n = 3, the x-values are [2, 5, 1] and y-values are [3, 4, 7]. The shuffled result should be [2, 3, 5, 4, 1, 7].

Input & Output

example_1.py — Basic Case
$ Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
💡 Note: The first half [2,5,1] represents x-values, second half [3,4,7] represents y-values. Interleaving gives us [x₁,y₁,x₂,y₂,x₃,y₃] = [2,3,5,4,1,7]
example_2.py — Minimum Case
$ Input: nums = [1,2,3,4], n = 2
Output: [1,3,2,4]
💡 Note: With n=2, x-values are [1,2] and y-values are [3,4]. The shuffle pattern gives [1,3,2,4]
example_3.py — Single Pair
$ Input: nums = [1,1], n = 1
Output: [1,1]
💡 Note: Edge case with only one pair: x₁=1, y₁=1, so result is [1,1]

Constraints

  • 1 ≤ n ≤ 500
  • nums.length == 2n
  • 1 ≤ nums[i] ≤ 103
  • Array contains exactly 2n elements

Visualization

Tap to expand
Perfect Shuffle VisualizationLeft Pile (X-cards)2X₁5X₂1X₃Right Pile (Y-cards)3Y₁4Y₂7Y₃Perfect Shuffle Result2pos 03pos 15pos 24pos 31pos 47pos 5Pattern: result[2*i] = X[i], result[2*i+1] = Y[i]Time: O(n) | Space: O(n) | One loop through n pairs
Understanding the Visualization
1
Split the Deck
Identify the two halves: X-cards [2,5,1] and Y-cards [3,4,7]
2
Recognize the Pattern
Each position in result follows: even positions get X-cards, odd positions get Y-cards
3
Perform Perfect Shuffle
Interleave one card from each pile: X₁,Y₁,X₂,Y₂,X₃,Y₃
4
Complete the Shuffle
Final arrangement: [2,3,5,4,1,7] - perfectly interleaved!
Key Takeaway
🎯 Key Insight: The shuffle follows a predictable mathematical pattern - each element at position i maps to position 2*i, and its pair at i+n maps to 2*i+1. This allows us to solve the problem optimally in a single pass!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
78.0K Views
High Frequency
~8 min Avg. Time
2.3K 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