Ride-hailing app~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-324sorting
A rides app tests its trip chart with a feed of speed readings that must zigzag. Each reading at an even place must be lower than the next reading, and each reading at an odd place must be higher than the next. Equal neighbours are not allowed. Many arrangements may work, so the test team builds the feed with one fixed rule.
Write wiggle_arrange(readings).
readings is the list of speed readings.(n + 1) // 2 values, and the upper half has the rest.r[0] < r[1] > r[2] < r[3] ....Input: readings = [1, 5, 1, 1, 6, 4]
Output: [1, 6, 1, 5, 1, 4]Sorted, the readings are 1, 1, 1, 4, 5, 6. The lower half is 1, 1, 1 and the upper half is 4, 5, 6. Fill each half from its largest value.
| Place | Half | Value taken | Reading placed |
|---|---|---|---|
| 0 | lower, from its largest | 1 | 1 |
| 1 | upper, from its largest | 6 | 6 |
| 2 | lower, from its largest | 1 | 1 |
| 3 | upper, from its largest | 5 | 5 |
| 4 | lower, from its largest | 1 | 1 |
| 5 | upper, from its largest | 4 | 4 |
The result [1, 6, 1, 5, 1, 4] alternates low and high.
Input: readings = [2, 2, 1, 3]
Output: [2, 3, 1, 2]The two 2s are split between the halves, and the result is [2, 3, 1, 2].
Input: readings = [1, 2, 3]
Output: [2, 3, 1]With 3 readings, the even places need 2 values, so the lower half takes the middle one: [2, 3, 1].
0 ≤ readings.length ≤ 100,0000 ≤ readings[i] ≤ 1,000,000Sorting costs n log n, which is about 1.7 million steps at n = 100,000. A selection sort costs n × n, which is 10^10. The sort is the only costly step; the filling pass costs n.