Wiggle Sort - Problem

Imagine you're creating a mountain range pattern with numbers! Given an integer array nums, your task is to rearrange the elements to create a "wiggle" pattern where elements alternate between smaller-or-equal and greater-or-equal relationships.

Specifically, reorder the array so that: nums[0] ≤ nums[1] ≥ nums[2] ≤ nums[3] ≥ nums[4]...

The pattern: Each element at an even index should be ≤ its right neighbor, and each element at an odd index should be ≥ its right neighbor. Think of it as creating peaks and valleys!

Input: An integer array with at least one element
Output: The same array rearranged in wiggle sort order
Guarantee: A valid wiggle arrangement always exists for the input.

Input & Output

example_1.py — Basic Case
$ Input: [3,5,2,1,6,4]
Output: [3,5,1,6,2,4]
💡 Note: One possible wiggle arrangement. The pattern shows: 3≤5≥1≤6≥2≤4, which satisfies the alternating ≤≥≤≥ requirement.
example_2.py — Small Array
$ Input: [6,6,5,6,3,8]
Output: [6,6,5,6,3,8]
💡 Note: With duplicates, the original array might already be valid: 6≤6≥5≤6≥3≤8. Notice that equal values (≤ and ≥) satisfy both conditions.
example_3.py — Two Elements
$ Input: [2,1]
Output: [1,2]
💡 Note: For a two-element array, we need nums[0] ≤ nums[1], so [1,2] works perfectly as 1≤2.

Visualization

Tap to expand
🏔️ Wiggle Sort: Mountain Range BuilderBefore: Chaotic Landscape352164After: Perfect Peak-Valley Pattern3516243 ≤ 5 ≥ 1 ≤ 6 ≥ 2 ≤ 4🎯 Algorithm MagicOne pass, local swaps → global wiggle pattern!Legend:Valley (even index)Peak (odd index)
Understanding the Visualization
1
Walk the Mountain Range
Start from the left and examine each position
2
Identify Misplaced Elements
Check if current position violates the peak-valley pattern
3
Local Correction
Swap with neighbor to fix the violation immediately
4
Continue Forward
Move to next position, previous fixes remain valid
Key Takeaway
🎯 Key Insight: Local fixes create global solutions! By ensuring each adjacent pair satisfies the wiggle condition, we automatically achieve a perfect mountain range pattern across the entire array.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the array, checking and potentially swapping each adjacent pair once

n
2n
Linear Growth
Space Complexity
O(1)

Only using a constant amount of extra space for the swapping operation

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 0 ≤ nums[i] ≤ 5000
  • The input array always has a valid wiggle sort arrangement
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24 Apple 18
52.4K Views
Medium-High Frequency
~15 min Avg. Time
1.8K 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