Skip to content
Problem 324 · LeetCode 324(opens in a new tab)

Wiggle Sort II

MediumArrays

You are given a list of whole numbers, nums. Rearrange it in place so that it goes up and down strictly: the first number is smaller than the second, the second is larger than the third, the third is smaller than the fourth, and so on to the end.

Every input has at least one valid arrangement. When several exist, any of them is accepted. The function returns nothing; it changes nums itself.

Example 1

Input:  nums = [2, 7, 2, 5, 3, 2]
Output: [2, 7, 2, 5, 2, 3]
Why:    2 < 7 > 2 < 5 > 2 < 3; other valid orders are fine too
1 more example and the constraints

Example 2

Input:  nums = [4, 4, 5, 6, 5]
Output: [5, 6, 4, 5, 4]
Why:    5 < 6 > 4 < 5 > 4

Constraints

  • 1 ≤ length of nums ≤ 50,000
  • 0 ≤ nums[i] ≤ 5,000
  • A valid arrangement always exists
  • Follow-up: O(n) time, or O(1) extra space

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort, then deal each half from its topO(n log n)
  2. Counting sort, deal from the topO(n + V)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 numbersVerdict
Sort, then dealO(n log n)
Passes; easy to explain
Counting sort, then dealO(n + V)
Best; linear time

n = length of nums, V = 5,001 possible values.

Edge cases to test

  • One number. [7] is already valid; there is no pair to compare.
  • Odd length. [4, 4, 5, 6, 5] has three valleys and two peaks, so the smaller half is the bigger one.
  • Many copies of the middle value. [2, 1, 2, 1, 2, 3] only works if the 2s are kept apart; dealing from the top does that.
  • Already sorted input. [0, 0, 1, 1, 2, 2, 2, 3] has to be fully rearranged.

Common mistakes

  • Dealing each half from the front, which puts equal middle values side by side.
  • Sorting nums itself and then reading from it while writing into it.
  • Swapping neighbours that are out of order, as in the easier Wiggle Sort: that only gives ≤ and ≥, not strict < and >.

How to talk through it

  1. 1Clarify. Strict inequalities? Is an answer guaranteed? Any valid order accepted?
  2. 2Split the values. Peaks must beat both neighbours, so the larger half goes on odd slots and the smaller half on even slots.
  3. 3Handle duplicates. Deal both halves from the top so copies of the median end up far apart.
  4. 4Drop the sort. Values stop at 5,000, so counting gives the same order in O(n + V).
  5. 5Test out loud. Run [4, 5, 5, 6], a single number and an odd length before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?