Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]...

The wiggle pattern means elements at even indices should be smaller than their next element, and elements at odd indices should be larger than their next element.

You may assume the input array always has a valid answer.

Input & Output

Example 1 — Basic Wiggle Pattern
$ Input: nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
💡 Note: One possible wiggle sort: 1 < 6 > 1 < 5 > 1 < 4. Each even index is smaller than the next odd index, and each odd index is larger than the next even index.
Example 2 — Small Array
$ Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]
💡 Note: After sorting [1,1,2,2,3,3], we arrange as wiggle: 2 < 3 > 1 < 3 > 1 < 2. Smaller elements at even positions, larger at odd positions.
Example 3 — Minimum Size
$ Input: nums = [1,2]
Output: [1,2]
💡 Note: For two elements, we need nums[0] < nums[1], so [1,2] already satisfies the wiggle condition.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 0 ≤ nums[i] ≤ 5000
  • It is guaranteed that there will be an answer for the given input.

Visualization

Tap to expand
Wiggle Sort II: Creating Alternating PatternInput Array:151164↓ Transform ↓Create wiggle pattern: nums[0] < nums[1] > nums[2] < nums[3]...Wiggle Result:161514< 6> 1< 5> 1< 4Pattern: 1 < 6 > 1 < 5 > 1 < 4 ✓
Understanding the Visualization
1
Input Array
Original unsorted array [1,5,1,1,6,4]
2
Wiggle Requirement
Need pattern: small < large > small < large...
3
Output Result
Wiggle sorted: [1,6,1,5,1,4]
Key Takeaway
🎯 Key Insight: Use virtual indexing to map wiggle positions to sorted order without extra space
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
87.0K Views
Medium Frequency
~25 min Avg. Time
1.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