Find K-th Smallest Pair Distance

Hard Topics Company Tags

For each pair of distinct indices i < j in nums, compute the distance abs(nums[i] - nums[j]). Sort all of these distances in nondecreasing order and return the value in position k, counting positions from 1. Equal distances from different index pairs occupy separate positions.

Example 1:

Input: nums = [0,4,9]
k = 2

Output: 5

Explanation: The three distances are 4, 9, and 5. In sorted order they are [4,5,9], whose second value is 5.

Example 2:

Input: nums = [2,2,7]
k = 1

Output: 0

Explanation: The two entries equal to 2 form a distance-zero pair. The other two pairs both have distance 5, so the smallest distance is 0.

Example 3:

Input: nums = [1,5,10]
k = 3

Output: 9

Explanation: The sorted distances are [4,5,9]. The third and largest distance is 9, produced by values 1 and 10.

Constraints:

  • 2 <= nums.length <= 10000
  • 0 <= nums[i] <= 1000000
  • 1 <= k <= nums.length * (nums.length - 1) / 2


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.