Ride-hailing app~18 min2s · 256 MBtarget O((n + q) log n) time, O(1) spacebinary-search
You work on a ride-hailing app. A long straight avenue has pickup points at known positions, listed from the start of the avenue, and two points can share a position. Riders stand at other positions along it.
Your team lead asks: "Where is the nearest pickup point for each rider?" When two points are equally near, riders walk to the one nearer the start of the avenue. There can be 100,000 points and 100,000 riders.
Write nearest_stops(stops, riders).
stops is sorted from the smallest position to the largest. Positions can repeat.riders[k] is the position of rider k.riders.Input: stops = [2, 5, 5, 9, 14], riders = [0, 7, 12, 20, 5, 3]
Output: [2, 5, 14, 14, 5, 2]For each rider, find the first stop at or after the rider with a binary search. The nearest stop is that one or the one before it.
| Rider | First stop at or after (index) | Candidate stops | Nearest |
|---|---|---|---|
| 0 | 0 | 2 | 2 |
| 7 | 3 | 5, 9 | 5 |
| 12 | 4 | 9, 14 | 14 |
| 20 | 5 | 14 | 14 |
| 5 | 1 | 2, 5 | 5 |
| 3 | 1 | 2, 5 | 2 |
The rider at 7 is a tie: 5 is 2 away and 9 is 2 away. The smaller position, 5, wins.
Input: stops = [10], riders = [1, 10, 99]
Output: [10, 10, 10]One stop is the nearest for every rider, near or far.
Input: stops = [4, 8], riders = [6, 5, 7]
Output: [4, 4, 8]Position 6 is 2 from both stops, and the smaller position 4 wins. Position 5 is nearer to 4, and position 7 is nearer to 8.
1 ≤ len(stops) ≤ 100,000, sorted from smallest to largest1 ≤ len(riders) ≤ 100,0000 ≤ stops[i], riders[k] ≤ 1,000,000,000Looking at every stop for every rider is 10 billion steps, which is too slow for a 2-second limit. The stops are already sorted, so a rider's nearest stop is next to the place where the rider would fit in the list. A binary search finds that place in about 17 steps.