Engineering platform~30 min2s · 256 MBtarget O(n log n + n log R) time, O(n) spaceclassic twin: lc-719binary-search-answer · two-pointers · sorting
A build system records the finish time, in seconds, of each build in a day. Engineers compare builds in pairs. The gap of a pair is the number of seconds between the two finish times.
Take all the pairs of builds. Sort their gaps from smallest to largest, and repeats count. What is the k-th gap in that sorted list?
Write kth_gap(finish_times, k).
i < j. Its gap is |finish_times[i] - finish_times[j]|.Input: finish_times = [1, 6, 1, 9, 4], k = 4
Output: 3Sorted, the times are [1, 1, 4, 6, 9]. The ten gaps in order are 0, 2, 3, 3, 3, 5, 5, 5, 8, 8, so the 4th is 3.
You do not list them. Instead, search the gap d in [0, 8]. For a gap d, count the pairs whose gap is at most d. The first d with a count of at least 4 is the answer.
| Step | lo | hi | mid | pairs with gap <= mid | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 5 | 5 >= 4, so hi = 4 |
| 2 | 0 | 4 | 2 | 2 | 2 < 4, so lo = 3 |
| 3 | 3 | 4 | 3 | 5 | 5 >= 4, so hi = 3 |
| end | 3 | 3 | the 4th gap is 3 |
Input: finish_times = [5, 5], k = 1
Output: 0One pair with a gap of 0. The answer is the bottom of the range.
Input: finish_times = [1, 3, 1], k = 3
Output: 2The gaps are 0, 2 and 2. Equal gaps from different pairs all count, so the 3rd gap is 2.
2 ≤ finish_times.length ≤ 100,000, in any order, repeats allowed0 ≤ finish_times[i] ≤ 1,000,000,000 (seconds)1 ≤ k ≤ n × (n − 1) / 2, the number of pairs; for n = 100,000 that is 4,999,950,000, which does not fit in 32 bitsThere are n × (n − 1) / 2 pairs, which is about 5 × 10^9 at n = 100,000. You cannot list them or sort them. But you can count how many pairs have a gap of at most d in about n steps after sorting. A binary search over d, up to 10^9, needs about 30 counts, so about 3 × 10^6 steps.