Maps app~20 min2s · 256 MBtarget O(n log k) time, O(k) spaceheaps · top-k
A ride-hailing app receives a ride request at a point on the city map. The dispatcher offers the ride to the closest drivers who are free.
Each driver has a map position and an idle flag. Distance counts blocks: the east-west gap plus the north-south gap. The dispatcher wants a short list, and it asks for the same list for every request, so the list must come out fast.
Write nearest_idle_drivers(xs, ys, idle, px, py, k).
i stands at (xs[i], ys[i]). The driver is free when idle[i] == 1 and busy when idle[i] == 0.(px, py). The distance of driver i is |xs[i] - px| + |ys[i] - py|.k free drivers with the smallest distance. When two drivers are equally far, the lower driver number comes first.k drivers are free, return all of them.Input: xs = [3, -2, 1, 5, -1, 0, 2], ys = [1, 4, -4, 0, 1, 6, -1], idle = [1, 1, 0, 1, 1, 1, 1], px = 0, py = 0, k = 3
Output: [4, 6, 0]The trace keeps the best drivers so far as pairs (distance, driver). Driver 2 is busy.
| i | Distance | Best drivers after this driver (distance, number) |
|---|---|---|
| 0 | 4 | (4, 0) |
| 1 | 6 | (4, 0), (6, 1) |
| 2 | busy | unchanged |
| 3 | 5 | (4, 0), (5, 3), (6, 1) |
| 4 | 2 | (2, 4), (4, 0), (5, 3); driver 1 leaves |
| 5 | 6 | unchanged; driver 5 is the worst, so it leaves at once |
| 6 | 3 | (2, 4), (3, 6), (4, 0); driver 3 leaves |
The kept drivers, nearest first, are 4, 6 and 0.
Input: xs = [4, 1], ys = [4, 1], idle = [1, 0], px = 0, py = 0, k = 3
Output: [0]Only driver 0 is free, so the list holds one driver even though k = 3.
Input: xs = [2, -2, 0], ys = [0, 0, 2], idle = [1, 1, 1], px = 0, py = 0, k = 2
Output: [0, 1]All three drivers are 2 blocks away. The lower numbers win, so drivers 0 and 1 are kept.
1 ≤ xs.length ≤ 100,000 (drivers in the area); ys and idle have the same length-1,000,000 ≤ xs[i], ys[i], px, py ≤ 1,000,000 (map coordinates in blocks)idle[i] is 0 or 11 ≤ k ≤ 1,000 (drivers the app can offer a ride to)Sorting every driver by distance costs about n log n, and picking the nearest one k times costs n × k, about 10^8 at the limits. A heap that holds only the best k drivers costs about n log k, about 10^6 here. The small k is the hint: you never need the order of all the drivers.