Ride-hailing app~12 min2s · 256 MBtarget O(n) time, O(n) spacesorting
A ride-hailing app keeps pending requests in a list, each with the seconds it has waited. The dispatcher takes the last request as a reference and splits the list around it in one pass. Requests that waited less than the reference move to the front.
The pass swaps values inside the list and builds no second list. After the pass, the reference sits in the place it would have in the sorted list.
Write partition_once(waits). Follow these steps exactly, because the result depends on the order of the swaps.
pivot be the last value, and let store be 0.j from 0 to the one before the last: if waits[j] < pivot, swap waits[store] with waits[j], and add 1 to store.waits[store] with the last value. Return the list.For an empty list, return an empty list. The input list is not changed; return a new list.
Input: waits = [7, 2, 9, 4, 6, 1, 5]
Output: [2, 4, 1, 5, 6, 9, 7]The pivot is 5. The table shows the scan.
| j | Value | Less than 5? | store after | List after |
|---|---|---|---|---|
| 0 | 7 | no | 0 | [7, 2, 9, 4, 6, 1, 5] |
| 1 | 2 | yes | 1 | [2, 7, 9, 4, 6, 1, 5] |
| 2 | 9 | no | 1 | [2, 7, 9, 4, 6, 1, 5] |
| 3 | 4 | yes | 2 | [2, 4, 9, 7, 6, 1, 5] |
| 4 | 6 | no | 2 | [2, 4, 9, 7, 6, 1, 5] |
| 5 | 1 | yes | 3 | [2, 4, 1, 7, 6, 9, 5] |
The last step swaps the values at places 3 and 6, which puts the pivot at place 3.
Input: waits = [4, 4, 4]
Output: [4, 4, 4]No value is less than the pivot, so store stays 0. The final swap exchanges two equal values.
Input: waits = [3, 1, 2]
Output: [1, 2, 3]The 3 stays. The 1 is less than 2, so it swaps to place 0. The final swap puts the 2 at place 1.
0 ≤ waits.length ≤ 100,000 (requests)0 ≤ waits[i] ≤ 1,000,000,000 (seconds)The pass visits each request once, so it costs about n steps. A version that builds a new list after every swap copies up to n values for each of up to n swaps. That is about 5 × 10^9 copies at n = 100,000.