All problems
1160MediumArrayDivide and ConquerGreedySortingQuickselect

Laying the Readings Out in a Zigzag

Tracked in this browser only
Write code

Trains the technique from

LeetCode 324Wiggle Sort II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def wiggle_sort(readings: list[int]) -> list[int]:
Java
public int[] wiggleSort(int[] readings)
September 7
Apply