Wiggle Sort - Problem

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

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

Example:

Input: nums = [3,5,2,1,6,4]
Output: [3,5,1,6,2,4]
Explanation: 3 <= 5 >= 1 <= 6 >= 2 <= 4

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,5,2,1,6,4]
Output: [3,5,1,6,2,4]
💡 Note: The array satisfies: 3 ≤ 5 ≥ 1 ≤ 6 ≥ 2 ≤ 4. Even indices are valleys (≤ next), odd indices are peaks (≥ next).
Example 2 — Already Wiggled
$ Input: nums = [1,3,2,4]
Output: [1,3,2,4]
💡 Note: Already satisfies wiggle: 1 ≤ 3 ≥ 2 ≤ 4. No changes needed.
Example 3 — Two Elements
$ Input: nums = [2,1]
Output: [1,2]
💡 Note: For two elements, ensure first ≤ second: swap to get 1 ≤ 2.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 0 ≤ nums[i] ≤ 5000

Visualization

Tap to expand
Wiggle Sort: Transform Array to Alternating PatternInput:352164No clear patternApply Wiggle Rule ↓Output:351624Perfect wiggle: valley-peak-valley-peak...
Understanding the Visualization
1
Input Array
Original array [3,5,2,1,6,4] with no pattern
2
Apply Wiggle Rule
Ensure nums[0] ≤ nums[1] ≥ nums[2] ≤ nums[3]...
3
Wiggle Pattern
Result [3,5,1,6,2,4] alternates valley-peak
Key Takeaway
🎯 Key Insight: Local swaps can fix wiggle violations without affecting already-correct portions
Asked in
Google 25 Facebook 20 Amazon 18 Microsoft 15
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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