Wiggle Sort II
Real-world version: Laying the Readings Out in a ZigzagThe statement here is our own: the same inputs, outputs and technique.
A row holds the readings readings. A zigzag is an arrangement of them where the first is below the second, the second is above the third, the third is below the fourth, and so on, strictly alternating all the way along.
Several zigzags may be possible, so the one wanted is pinned down like this. Put the readings in non-decreasing order and cut them into a lower part holding the first half, rounded up when the count is odd, and an upper part holding the rest. Fill positions 0, 2, 4 and onwards from the lower part taken back to front, and positions 1, 3, 5 and onwards from the upper part taken back to front.
Return that arrangement. The readings always allow a zigzag.
Examples
Example 1
- Input
- readings = [1, 2, 3]
- Output
- [2, 3, 1]
In order the readings are 1, 2 and 3. The lower part holds 1 and 2 and the upper part holds 3, and taking each from the back gives 2, then 3, then 1.
Example 2
- Input
- readings = [1, 1, 2]
- Output
- [1, 2, 1]
The lower part holds the two 1 readings and the upper part the 2, so the 2 lands between them.
Example 3
- Input
- readings = [0, 0, 1, 1]
- Output
- [0, 1, 0, 1]
The lower part holds the two zeros and the upper part the two ones, and taking each from the back alternates them.
Constraints
- 1 <= readings.length <= 5 * 10^4
- 0 <= readings[i] <= 5000
- the readings always allow a zigzag
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def wiggle_sort(readings: list[int]) -> list[int]:public int[] wiggleSort(int[] readings)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Kth Largest Element in an ArrayReal-world version: Kth Highest Daily SwingMedium
- K Closest Points to OriginReal-world version: Nearest Survey StakesMedium
- Query Kth Smallest Trimmed NumberReal-world version: Kth Smallest Serial by Its TailMedium
- Majority ElementReal-world version: Quorum Drift ValueEasy