Maps app~15 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting
A maps app shows pins along a hiking trail. Each pin is a viewpoint, given as its distance from the start in metres. All the pins are at different distances.
A designer worries that some pins are too close together on the screen. Your team lead asks: which pairs of pins are closest, that is, have the smallest distance between them?
Write closest_pairs(positions).
positions holds the distances of the pins from the start, in no particular order. All the values are different, and there are at least two.[lower, higher], and list the pairs in increasing order of the lower position.Input: positions = [8, 3, 12, 5, 1, 10]
Output: [[1, 3], [3, 5], [8, 10], [10, 12]]Sorted, the positions are 1, 3, 5, 8, 10, 12. The gaps between neighbours are 2, 2, 3, 2, 2. The smallest is 2, and it appears 4 times.
| Neighbours | Gap | Smallest? |
|---|---|---|
| 1 and 3 | 2 | yes |
| 3 and 5 | 2 | yes |
| 5 and 8 | 3 | no |
| 8 and 10 | 2 | yes |
| 10 and 12 | 2 | yes |
The answer is [[1, 3], [3, 5], [8, 10], [10, 12]].
Input: positions = [5, 6]
Output: [[5, 6]]Two pins at 5 and 6: one pair, with distance 1.
Input: positions = [100, 0]
Output: [[0, 100]]The pins are at 100 and 0. The pair is written with the lower position first.
2 ≤ length of positions ≤ 10^50 ≤ positions[i] ≤ 10^6There are about 5 x 10^9 pairs of pins when n is 100,000. Looking at every pair, even once, is too slow.
Sorting takes about n log n = 1.7 x 10^6 steps. After sorting, the closest pins are neighbours, so only n - 1 gaps need a look.
The answer can hold up to n - 1 pairs, when every gap is equal.