Wiggle Sort II - Problem
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code