> ## 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 II Python Solution with Tests

> Tested Python solution for LeetCode 324 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 324, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Divide and Conquer](/catalog/topics/divide-and-conquer), [Greedy](/catalog/topics/greedy), [Sorting](/catalog/topics/sorting), Quickselect. [View on LeetCode](https://leetcode.com/problems/wiggle-sort-ii/description/).

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

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 324   # by problem number
lcpy gen -s wiggle_sort_ii   # 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.

### Examples

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

```
Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]
```

### Constraints

* `1 <= nums.length <= 5 * 10^4`
* `0 <= 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

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log n)
    # Space: O(n)
    def wiggle_sort(self, nums: list[int]) -> None:
        sorted_nums = sorted(nums)
        n = len(nums)
        nums[::2] = sorted_nums[: (n + 1) // 2][::-1]
        nums[1::2] = sorted_nums[(n + 1) // 2 :][::-1]
```

## Complexity

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

## Tags


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