Find K-th Smallest Pair Distance
Input:
nums = [1,3,1]
k = 1
Output: 0
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.def enough(distance) -> bool: # two pointers
count, i, j = 0, 0, 0
while i < n or j < n:
while j < n and nums[j] - nums[i] <= distance: # move fast pointer
j += 1
count += j - i - 1 # count pairs
i += 1 # move slow pointer
return count >= kdef smallestDistancePair(nums: List[int], k: int) -> int:
nums.sort()
n = len(nums)
left, right = 0, nums[-1] - nums[0]
while left < right:
mid = left + (right - left) // 2
if enough(mid):
right = mid
else:
left = mid + 1
return leftLast updated