Ride-hailing app~40 min2s · 256 MBtarget O(n log n) time, O(n) spacedivide-and-conquer
A ride-sharing app has n riders waiting, each at whole-number map coordinates. To pool a ride, the app looks for the two riders who are closest to each other.
To avoid square roots, the app compares squared distances: the squared distance between (x1, y1) and (x2, y2) is (x1 - x2)² + (y1 - y2)². Your team lead asks: "What is the smallest squared distance between any two riders?" Up to 100,000 riders can wait at once.
Write closest_pair_squared(riders).
riders[i] = [x, y] is the position of rider i. Two riders can wait at the same position.0.Input: riders = [[1, 1], [9, 2], [4, 4], [5, 5], [8, 8], [2, 7]]
Output: 2Sorted by x, the riders are (1, 1), (2, 7), (4, 4), (5, 5), (8, 8), (9, 2). Split after the third:
| Step | Result |
|---|---|
| Left half (1, 1), (2, 7), (4, 4) | The smallest squared distance is 13, between (2, 7) and (4, 4) |
| Right half (5, 5), (8, 8), (9, 2) | The smallest squared distance is 18 |
| Best so far | 13, and the middle line is at x = 5 |
| Strip: riders with (x - 5)² < 13, in order of y | (4, 4), (5, 5), (2, 7), (8, 8) |
| Compare (4, 4) with (5, 5) | The squared distance is 2, a new best |
The answer is 2, between (4, 4) and (5, 5), which sit in different halves.
Input: riders = [[0, 0], [3, 4]]
Output: 25With two riders there is one pair: 3² + 4² = 25.
Input: riders = [[2, 2], [7, 1], [2, 2]]
Output: 0Two riders share a position.
2 ≤ len(riders) ≤ 100,000-1,000,000 ≤ x, y ≤ 1,000,000Comparing every pair takes about 5 billion steps for 100,000 riders, which is far beyond a 2-second limit. The pairs have to be pruned: most of them cannot be the closest pair, and a quick test must rule them out.