> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Wiggle Sort Python Solution with Tests

> Tested Python solution for LeetCode 280 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 280, [Medium](/catalog/medium). Topics: [Greedy](/catalog/topics/greedy), [Array](/catalog/topics/array), [Sorting](/catalog/topics/sorting). [View on LeetCode](https://leetcode.com/problems/wiggle-sort/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 280   # by problem number
lcpy gen -s wiggle_sort   # by problem name
```

## 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.

**Follow up:** Could you solve the problem in `O(n)` time complexity?

### Examples

```
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.
```

```
Input: nums = [6,6,5,6,3,8]
Output: [6,6,5,6,3,8]
```

### Constraints

* `1 <= nums.length <= 5 * 10^4`
* `0 <= nums[i] <= 10^4`
* It is guaranteed that there will be an answer for the given input `nums`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/wiggle_sort/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/wiggle_sort/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def wiggle_sort(self, nums: list[int]) -> None:
        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 - 1], nums[i] = nums[i], nums[i - 1]
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.