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
Wiggle Sort II - Virtual Indexing INPUT Original Array nums[] 1 [0] 5 [1] 1 [2] 1 [3] 6 [4] 4 [5] Required Wiggle Pattern: small large small large small large nums[0] < nums[1] > nums[2] < nums[3] > nums[4]... n = 6 elements ALGORITHM STEPS 1 Find Median (Quickselect) O(n) to find middle value Sorted: [1,1,1,4,5,6] Median = 4 2 Virtual Index Mapping Map i --> (1+2*i) % (n|1) 0-->1, 1-->3, 2-->5, 3-->0, 4-->2, 5-->4 3 3-Way Partition Dutch National Flag algo Large-->odd, Small-->even idx > median = median < median 4 In-Place Rearrange Place via virtual indices Odd idx: large values Even idx: small values Time: O(n) | Space: O(1) FINAL RESULT Wiggle Sorted Array: 1 [0] 6 [1] 1 [2] 5 [3] 1 [4] 4 [5] Verification: 1 < 6 [OK] (idx 0,1) 6 > 1 [OK] (idx 1,2) 1 < 5 [OK] (idx 2,3) 5 > 1 [OK] (idx 3,4) 1 < 4 [OK] (idx 4,5) 1 6 1 5 1 4 Wiggle Pattern Valid! Key Insight: Virtual indexing maps logical positions to physical array locations, allowing in-place O(1) space rearrangement. Formula (1+2*i)%(n|1) interleaves odd/even indices: large values go to odd positions, small values to even positions. Combined with 3-way partition around median, this ensures the wiggle property: even[i] < odd[i] > even[i+1]. TutorialsPoint - Wiggle Sort II | Virtual Indexing with Quickselect Approach
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
87.0K Views
Medium Frequency
~25 min Avg. Time
1.5K 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