Problem 357749 · hard · Level 03 Linear Management & Searching

Gaps Between Every Pair of Houses

binary search on the answer · two pointers · sorting

Houses stand along a straight road at the positions in nums (two houses facing each other share a position). For every pair of different houses i < j the distance between them is |nums[i] - nums[j]|. Put all these distances in increasing order, keeping equal ones as separate entries, and return the k-th.

Examples

Input:  nums = [9, 4, 6, 4], k = 1
Output: 0
Explanation: the distances are 5, 3, 5, 2, 0, 2.

Input:  nums = [2, 7, 3, 2], k = 4
Output: 4
Explanation: the six distances in order are 0, 1, 1, 4, 5, 5.

Input:  nums = [8, 1, 3], k = 3
Output: 7

Constraints

  • 2 <= len(nums) <= 5 * 10**4, 0 <= nums[i] <= 10**6
  • 1 <= k <= len(nums) * (len(nums) - 1) / 2
  • Required time: O(n log n + n log(max - min)). There can be over a billion pairs.

Goals

  • Count pairs with distance <= d in linear time after sorting
  • Binary search the distance instead of enumerating pairs
Starting Python…