Wiggle Sort — LeetCode 280 Python Solution

MediumLeetCode PremiumGreedyArraySorting
Problem
#280
Pattern
Greedy
Reading time
2 min

The problem

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

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.

Python solution

Python
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)):
            if (i % 2 == 1 and nums[i] < nums[i - 1]) or (
                i % 2 == 0 and nums[i] > nums[i - 1]
            ):
                nums[i], nums[i - 1] = nums[i - 1], nums[i]

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 280. Wiggle Sort is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 280. Wiggle Sort?
LeetCode 280. Wiggle Sort is rated Medium on LeetCode.
What topics does LeetCode 280. Wiggle Sort cover?
LeetCode 280. Wiggle Sort is tagged Greedy, Array and Sorting on LeetCode.
Is LeetCode 280. Wiggle Sort a premium problem?
Yes. LeetCode 280. Wiggle Sort is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview