Maps app~20 min2s · 256 MBtarget O(n log n) time, O(n) spacedivide-and-conquer
A maps app places n pickup points along one straight road. Each point is a position in metres, and the points arrive in any order. Two points may share a position.
To suggest merging pickup points, you need the smallest gap between any two of them.
Your team lead says: Comparing every pair is too slow for a city. Split the points in halves, and think about the pairs that sit on both sides.
Write closest_gap(positions).
Input: positions = [9, 2, 15, 5]
Output: 3Each call splits its part in two, solves both, and merges the sorted halves. The smallest gap of a merged run is the least difference between neighbours.
| Call on points | Gap in the left half | Gap in the right half | Merged run | Smallest gap |
|---|---|---|---|---|
| [9, 2] | none | none | [2, 9] | 7 |
| [15, 5] | none | none | [5, 15] | 10 |
| [9, 2, 15, 5] | 7 | 10 | [2, 5, 9, 15] | 3 |
The closest pair is 2 and 5, which sit on different sides of the first split.
Input: positions = [40, 7, 7, 90]
Output: 0Two points share a position, so the answer is 0.
Input: positions = [100, 1]
Output: 99Two points make one pair, and the gap is 99.
2 ≤ positions.length ≤ 60,0000 ≤ positions[i] ≤ 1,000,000With 60,000 points there are 1,799,970,000 pairs. Even at a billion comparisons a second that is about two seconds in a fast language, and Python is far slower. A split into halves needs about 960,000 steps instead.