We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Wiggle Sort

Number: 280

Difficulty: Medium

Paid? Yes

Companies: Google, Myntra


Problem Description

Given an integer array nums, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3] ... . It is guaranteed that the input always has a valid answer.


Key Insights

  • The alternating "wiggle" requirement can be satisfied by ensuring two conditions:
    • For every odd index i, nums[i] should be greater than or equal to nums[i-1].
    • For every even index i (where i > 0), nums[i] should be less than or equal to nums[i-1].
  • A single pass through the array can ensure these conditions by swapping adjacent elements when the condition is violated.
  • This greedy approach works because the local adjustments guarantee the overall wiggle pattern without needing to sort the entire array.

Space and Time Complexity

Time Complexity: O(n) — Only one pass through the array is needed. Space Complexity: O(1) — The modifications are done in-place without extra data structures.


Solution

We can achieve a wiggle sort in one pass by iterating through the array and, at each index i (starting from 1), checking if the pair (nums[i-1], nums[i]) satisfies the wiggle condition. If i is odd, nums[i] should be at least nums[i-1]; if not, we swap them. Conversely, if i is even and nums[i] is greater than nums[i-1], then we swap them. These local swaps adjust the order incrementally while ensuring that the overall wiggle pattern is maintained. This greedy approach works because only two adjacent numbers are involved in any violation and fixing them locally does not disturb the rest of the order.


Code Solutions

# Python solution for Wiggle Sort
def wiggleSort(nums):
    # Iterate over the list starting from index 1
    for i in range(1, len(nums)):
        # Check the condition based on the parity of the index
        if i % 2 == 1:
            # For odd index, if previous element is greater, swap them
            if nums[i] < nums[i-1]:
                nums[i], nums[i-1] = nums[i-1], nums[i]
        else:
            # For even index, if previous element is smaller, swap them
            if nums[i] > nums[i-1]:
                nums[i], nums[i-1] = nums[i-1], nums[i]
    return nums

# Example usage:
# nums = [3,5,2,1,6,4]
# print(wiggleSort(nums))
← Back to All Questions