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 - One Pass Greedy INPUT nums = [3, 5, 2, 1, 6, 4] 3 i=0 5 i=1 2 i=2 1 i=3 6 i=4 4 i=5 Required Pattern: [0] <= [1] >= [2] <= [3]... Even index i: nums[i] <= nums[i+1] Odd index i: nums[i] >= nums[i+1] Length: 6 elements Valid answer guaranteed ALGORITHM STEPS 1 Iterate from i=0 Loop through array 2 Check index parity Even or odd position? 3 Verify condition Compare with next 4 Swap if violated Fix local order Trace Example: i=0: 3<=5? YES [3,5,2,1,6,4] i=1: 5>=2? YES [3,5,2,1,6,4] i=2: 2<=1? NO --> swap Result: [3,5,1,2,6,4] i=3: 2>=6? NO --> swap Result: [3,5,1,6,2,4] i=4: 2<=4? YES - Done! FINAL RESULT Output: [3, 5, 1, 6, 2, 4] 3 5 1 6 2 4 3 5 1 6 2 4 Verification: 3 <= 5 OK 5 >= 1 OK 1 <= 6 OK, 6 >= 2 OK, 2 <= 4 OK Complexity: Time: O(n) - single pass Space: O(1) - in-place Key Insight: The greedy approach works because fixing a violation at position i doesn't break the previous positions. When we swap nums[i] and nums[i+1], if nums[i-1] was valid before, it remains valid after the swap because we only make the current element smaller (even i) or larger (odd i) as needed. TutorialsPoint - Wiggle Sort | One Pass Greedy Approach
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