Maps app~25 min2s · 256 MBtarget O(q log n) time, O(1) spaceclassic twin: lc-658binary-search
A maps app shows the bus stops along one straight street. Each stop has a distance in metres from the start of the street, and the stops are listed in increasing order.
When a rider stands at a position on the street, the app shows the k stops nearest to them. If two stops are equally near, the app prefers the one with the smaller distance. The nearest stops always sit next to each other in the list, so the app only needs the position where that block starts.
Write closest_blocks(stops, k, targets).
stops is the sorted list of stop distances, with no repeats. k is how many stops to show.x, the nearest k stops are chosen by the smallest |stop - x|, and a tie goes to the smaller stop.stops of the first stop in the block of k nearest stops.Input: stops = [1, 3, 4, 8, 10, 15], k = 3, targets = [5, 0, 20, 9, 2]
Output: [1, 0, 3, 2, 0]A block of k = 3 stops can start at position 0, 1, 2 or 3. The search window [lo, hi) holds the starts that still need a test, [0, 3). The last start, 3, never needs one: it is the answer when every earlier start loses to the next.
Take the target 9. For a start mid, compare how far the first stop of the block is from 9 with how far the next stop outside the block is.
| Step | lo | hi | mid | first stop | next stop | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 3 | 1 | 3 (6 away) | 10 (1 away) | 6 > 1, the block should move right, so lo = 2 |
| 2 | 2 | 3 | 2 | 4 (5 away) | 15 (6 away) | 5 is not more than 6, so hi = 2 |
| end | 2 | 2 | the block starts at position 2: stops 4, 8, 10 |
The target 5 gets the block 3, 4, 8, so position 1. The target 0 gets 1, 3, 4, so position 0. The target 20 gets 8, 10, 15, so position 3.
The target 2 is 1 away from both 1 and 3. The tie goes to the smaller stop, so the block is 1, 3, 4 at position 0.
Input: stops = [7], k = 1, targets = [0, 7, 99]
Output: [0, 0, 0]With one stop, the block is that stop for every target.
Input: stops = [2, 5, 9, 14], k = 4, targets = [0, 6, 100]
Output: [0, 0, 0]When k equals the number of stops, the block is the whole list, so every answer is 0.
1 ≤ stops.length ≤ 100,000, and stops is strictly increasing: sorted, with no repeats1 ≤ k ≤ stops.length0 ≤ targets.length ≤ 100,0000 ≤ stops[i], targets[j] ≤ 1,000,000 (metres along the street)Sorting all the stops by distance for every target costs about n log n per target, which is far beyond the limit for 100,000 targets. The k nearest stops of a sorted list always form one block of neighbours, so you only need to find where the block starts. One binary search over the possible starts does it in about 17 steps.