Wiggle Sort II Problem
Description
LeetCode Problem 324.
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 1:
Input: nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Explanation: [1,4,1,5,1,6] is also accepted.
Example 2:
Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]
Constraints:
1 <= nums.length <= 5 * 10^40 <= nums[i] <= 5000- It is guaranteed that there will be an answer for the given input
nums.
Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?
Solution
Approach: Sort, Then Interleave the Halves Backwards
After sorting, the smaller half of the numbers should go to the even indexes (the valleys) and the larger half to the odd indexes (the peaks). With n numbers, the even indexes take the first (n + 1) / 2 sorted values and the odd indexes the rest.
The tricky part is equal values, which must never end up next to each other. Take [4, 5, 5, 6]. Filling both halves from smallest to largest gives [4, 5, 5, 6], which breaks at 5, 5: the largest value of the small half sits next to the smallest value of the large half, and those can be equal.
The fix is to fill both halves from largest to smallest:
- Even indexes
0, 2, 4, ...take the small half from its end:arr[(n - 1) / 2],arr[(n - 1) / 2 - 1], ... - Odd indexes
1, 3, 5, ...take the large half from its end:arr[n - 1],arr[n - 2], ...
For [4, 5, 5, 6] this gives [5, 6, 4, 5]. Now the copies of the middle value go to opposite ends of the array: in the small half they are the largest, so they go to the first valleys; in the large half they are the smallest, so they go to the last peaks. Since a valid answer exists, no value appears more than about half the time, so these copies never meet.
Each odd slot holds a value from the large half, which is at least every value in the small half, and strictly greater than its neighbors once the duplicates are kept apart like this.
Complexity: O(n log n) time for the sort and O(n) extra space for the sorted copy. The follow-up's O(n) time and O(1) space needs a median selection (quickselect) plus a 3-way partition with virtual indexes, which is much harder to get right.
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
arr = sorted(nums)
n = len(nums)
# Even slots get the smaller half, odd slots the larger half, both from largest to smallest,
# so copies of the median land as far apart as possible.
small, large = (n - 1) // 2, n - 1
for k in range(n):
if k % 2 == 0:
nums[k] = arr[small]
small -= 1
else:
nums[k] = arr[large]
large -= 1