Asked at

Wiggle Sort II

Hard
Verified
QuickselectSortingArray~35 min

Reorder nums so that nums[0] < nums[1] > nums[2] < nums[3] ... with every comparison strict.

Sort, then interleave the smaller half into even indices and the larger half into odd indices, filling from the back so equal values never touch.

The input arrives as a single array nums. Return the reordered array.

Examples

in[1, 5, 1, 1, 6, 4]
out[1, 6, 1, 5, 1, 4]

1 < 6 > 1 < 5 > 1 < 4 holds strictly.

in[1, 3, 2, 2, 3, 1]
out[2, 3, 1, 3, 1, 2]

Equal values are kept apart so each comparison is strict.

Constraints

  • 1 ≤ nums.length ≤ 5·10⁴
  • 0 ≤ nums[i] ≤ 5000
  • A valid wiggle ordering is guaranteed to exist.

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.