Ride-hailing app~10 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting
A ride-hailing dispatcher keeps a list of waiting pickup requests. Each entry is how long that rider has waited, in seconds.
The dispatcher screen must show the longest wait first. Before it redraws the screen, the app wants to know how many rows will show a different wait than they do now.
You get the list in its current order. Sort it from the longest wait to the shortest, and count the rows that change.
Write moved_requests(waits).
waits[i] is the wait of the request in row i, in seconds.i where the sorted list, longest wait first, shows a different wait than waits[i].Input: waits = [30, 90, 60, 10]
Output: 3Sorted from the longest wait, the list is 90, 60, 30, 10.
| Row | Now | Sorted | Different? |
|---|---|---|---|
| 0 | 30 | 90 | yes |
| 1 | 90 | 60 | yes |
| 2 | 60 | 30 | yes |
| 3 | 10 | 10 | no |
Three rows change, so the answer is 3.
Input: waits = [50, 40, 30]
Output: 0The list is already in order, so no row changes.
Input: waits = [5, 5, 9]
Output: 2Sorted, the list is 9, 5, 5. Row 0 changes from 5 to 9 and row 2 changes from 9 to 5. Row 1 shows 5 both times.
0 ≤ waits.length ≤ 100,000 (waiting requests)0 ≤ waits[i] ≤ 86,400 (seconds in one day)Finding the longest remaining wait for every row, as a hand sort does, costs about n × n / 2 steps, which is 5 × 10^9 at n = 100,000. A comparison sort needs about n log n comparisons, which is under 2 × 10^6 for the same n.