Ride-hailing app~30 min2s · 256 MBtarget O(n log n + n log R) time, O(n) spaceclassic twin: lc-2616binary-search-answer · greedy · sorting
A ride-hailing app offers shared rides. It has a list of riders, each with a requested pickup time in seconds. It wants to put riders into pairs, and a rider can be in only one pair.
The wait for a pair is the difference between the two pickup times. The app wants pairs pairs, and it wants the longest wait among them to be as short as possible. What is that smallest possible longest wait?
Write min_widest_gap(pickups, pairs).
pickups[i] is the requested pickup time of rider i.pairs pairs of different riders. No rider is in two pairs. The gap of a pair is |pickups[i] - pickups[j]|.pairs = 0, the answer is 0.Input: pickups = [12, 4, 30, 15, 1, 8], pairs = 2
Output: 3Sort the times: [1, 4, 8, 12, 15, 30]. To check a gap d, walk the sorted list. If the next time is at most d after this one, pair them and skip both. Otherwise move on by one.
The answer lies between 0 and the spread, 29. Search the window [lo, hi], where hi always works.
| Step | lo | hi | mid | pairs found at mid | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 29 | 14 | 2 | 2 >= 2, so hi = 14 |
| 2 | 0 | 14 | 7 | 2 | 2 >= 2, so hi = 7 |
| 3 | 0 | 7 | 3 | 2 | 2 >= 2, so hi = 3 |
| 4 | 0 | 3 | 1 | 0 | 0 < 2, so lo = 2 |
| 5 | 2 | 3 | 2 | 0 | 0 < 2, so lo = 3 |
| end | 3 | 3 | the answer is 3 |
At gap 3 the pairs are (1, 4) and (12, 15), both with a gap of 3.
Input: pickups = [5], pairs = 0
Output: 0With no pairs wanted, the longest wait is 0, the lower end of the window.
Input: pickups = [1, 2, 3, 100], pairs = 2
Output: 97Two pairs use all four riders. The rider at 100 must be paired with someone, and the best choice is 3, so the answer is 97, with the pairs (1, 2) and (3, 100).
0 ≤ pickups.length ≤ 100,0000 ≤ pickups[i] ≤ 1,000,000,000 (seconds since the start of the day)0 ≤ pairs and 2 × pairs ≤ pickups.length, so enough riders existThere are about n² / 2 possible pairs, which is 5 × 10^9 at n = 100,000, and many more ways to choose several of them. You need an approach of about n log n. Sorting costs n log n, and one greedy pass costs n. A binary search over the gap, up to 10^9, needs about 30 passes.