Ride-hailing app~25 min2s · 256 MBtarget O(n log k) time, O(k) spaceheaps · sorting
A rides app receives trip times from drivers' phones, and network delays shuffle them a little. A time never arrives more than k places away from where it belongs in sorted order. The app wants the sorted list as soon as possible, and it knows k. Sorting the whole list again from scratch wastes the information in k.
Write sort_nearly_sorted(values, k).
values is a list of whole numbers. Each value is at most k places from its position in the sorted list.k: the work should depend on n and k, not only on n.Input: values = [3, 1, 2, 6, 4, 5], k = 2
Output: [1, 2, 3, 4, 5, 6]Keep a min-heap of the latest values. Once it holds more than k values, the smallest one is final, so write it out.
| Written so far | Value added | Values in the heap | Smallest, written out |
|---|---|---|---|
| 0 | 3 | [3] | none yet |
| 0 | 1 | [1, 3] | none yet |
| 1 | 2 | [1, 2, 3] | 1 |
| 2 | 6 | [2, 3, 6] | 2 |
| 3 | 4 | [3, 4, 6] | 3 |
| 4 | 5 | [4, 5, 6] | 4 |
| 5 | none | [5, 6] | 5 |
| 6 | none | [6] | 6 |
Writing out the smallest values in turn gives [1, 2, 3, 4, 5, 6].
Input: values = [1, 2, 3], k = 0
Output: [1, 2, 3]With k = 0 the list is already sorted: [1, 2, 3].
Input: values = [4, 3, 2, 1], k = 3
Output: [1, 2, 3, 4]Here every value may be up to 3 places away, so the heap holds all of them: [1, 2, 3, 4].
0 ≤ values.length ≤ 100,0000 ≤ values[i] ≤ 1,000,000,0000 ≤ k ≤ 100,000, and every value is at most k places from its sorted position.Selecting the smallest value n times costs about n × n, which is 10^10 at n = 100,000. A heap of k + 1 values costs log k per step, so the whole job costs n log k.