Given an integer array nums, transform it into a wiggle array where elements alternate between peaks and valleys in a strict pattern: nums[0] < nums[1] > nums[2] < nums[3] > nums[4] < nums[5]...
Think of it like creating a zigzag mountain range where each peak is higher than its neighboring valleys, and each valley is lower than its neighboring peaks. The pattern must be strictly alternating - no equal adjacent elements allowed!
Example:[1,5,1,1,6,4] โ [1,6,1,5,1,4] creates the pattern: small < large > small < large > small < large
You're guaranteed that a valid wiggle arrangement always exists for the input array.
Input & Output
example_1.py โ Basic Wiggle Sort
$Input:[1,5,1,1,6,4]
โบOutput:[1,6,1,5,1,4]
๐ก Note:The output follows the wiggle pattern: 1 < 6 > 1 < 5 > 1 < 4. Each element at even index is smaller than its neighbors, and each element at odd index is larger than its neighbors.
example_2.py โ Small Array
$Input:[1,3,2]
โบOutput:[2,3,1]
๐ก Note:For a 3-element array, we need: small < large > small. So 2 < 3 > 1 satisfies the wiggle condition perfectly.
example_3.py โ Duplicate Elements
$Input:[1,1,2,2,3,3]
โบOutput:[2,3,1,3,1,2]
๐ก Note:Even with duplicates, we can create a valid wiggle pattern by strategically placing elements: 2 < 3 > 1 < 3 > 1 < 2.
Constraints
1 โค nums.length โค 5 ร 104
0 โค nums[i] โค 5000
You may assume the input array always has a valid answer
The array is modified in-place with O(1) extra memory for the optimal solution
The optimal approach uses a sort + two-pointers strategy with virtual indexing to create the perfect wiggle pattern. Key insight: median-based partitioning with reverse placement ensures no adjacent conflicts while maintaining the alternating small < large > small pattern.
Common Approaches
Approach
Time
Space
Notes
โ
Quickselect + Optimal Placement
O(n)
O(n)
Use quickselect to find median, then place elements optimally without full sorting
Brute Force (Try All Permutations)
O(n! ร n)
O(n)
Generate all possible arrangements and check which one satisfies the wiggle condition
Sort + Two Pointers Strategy
O(n log n)
O(n)
Sort array, then use strategic placement with two pointers to create wiggle pattern