Wiggle Sort Problem
Description
LeetCode Problem 280.
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 = [3,5,2,1,6,4]
Output: [3,5,1,6,2,4]
Explanation: [1,6,2,5,3,4] is also accepted.
Example 2:
Input: nums = [6,6,5,6,3,8]
Output: [6,6,5,6,3,8]
Constraints:
1 <= nums.length <= 5 * 10^40 <= nums[i] <= 10^4- It is guaranteed that there will be an answer for the given input
nums.
Follow up: Could you solve the problem in O(n) time complexity?
Solution
Approach: One Pass of Local Swaps
Sorting the array and swapping neighbors works, but it takes O(n log n). We can do it in one pass because each position only has to agree with its left neighbor:
- At an odd index
i, we neednums[i - 1] <= nums[i]. - At an even index
i, we neednums[i - 1] >= nums[i].
Walk from left to right, and whenever the pair nums[i - 1], nums[i] is in the wrong order, swap it.
Why doesn't a swap break the pair before it? Take an odd i where nums[i - 1] > nums[i]. The earlier pair already has nums[i - 2] >= nums[i - 1], so nums[i - 2] is also larger than nums[i]. After the swap, nums[i - 1] holds the smaller value nums[i], so nums[i - 2] >= nums[i - 1] still holds. The even case is the same with the inequalities flipped. So the prefix stays valid all the way to the end.
Many outputs are valid (Example 1 shows two), and any of them is accepted.
Complexity: O(n) time and O(1) extra space.
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(1, len(nums)):
# Odd i needs nums[i - 1] <= nums[i], even i needs nums[i - 1] >= nums[i].
if (i % 2 == 1 and nums[i - 1] > nums[i]) or (i % 2 == 0 and nums[i - 1] < nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]