Python coding

K-th smallest distance among pairs

Given a list nums of n >= 2 integers (values may repeat) and an integer k, look at every pair of positions i < j and its distance abs(nums[i] - nums[j]). There are n(n − 1)/2 distances, duplicates included. Return the k-th smallest of them, counting from 1 (1 <= k <= n(n − 1)/2).

For example, [1, 6, 3] has the distances 5, 2 and 3, so k = 1 gives 2. Aim for O(n log n + n log W), where W = max(nums) − min(nums): listing every pair is O(n²).

Besides the tests, one large input (2,000 values) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • kth_smallest_distance([1,6,3], 1) → 2
  • kth_smallest_distance([1,6,3], 3) → 5
  • kth_smallest_distance([4,4,9,1], 2) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Don't list the pairs: binary search the answer. "At least k pairs have distance <= d" is false, then true, as d grows; the answer is the first d where it turns true.

Hint 2

Sort nums first. Then count the pairs within d in O(n) with two pointers: for each right, advance left while nums[right] - nums[left] > d, and add right - left.

Hint 3

Search d in [0, max − min]. The first d whose count reaches k is always a real pair distance, because the count only changes at those values.

Solution and why it works
pythonO(n log n + n log W), W = max − min · O(n) for the sorted copy
def kth_smallest_distance(nums: list[int], k: int) -> int:
    nums = sorted(nums)

    def pairs_within(d: int) -> int:          # pairs at distance <= d, two pointers
        count = left = 0
        for right, x in enumerate(nums):
            while x - nums[left] > d:
                left += 1
            count += right - left
        return count

    lo, hi = 0, nums[-1] - nums[0]            # the answer is a distance in [lo, hi]
    while lo < hi:
        mid = (lo + hi) // 2
        if pairs_within(mid) >= k:
            hi = mid
        else:
            lo = mid + 1
    return lo

The number of pairs at distance <= d only grows with d, so the answer is the first d whose count reaches k: binary search over [0, max − min]. On sorted values, the pairs that end at right within d start at left or later, and left never moves back, so one count is O(n): O(n log n + n log W) in all. The trap is generating all n(n − 1)/2 distances and sorting them: O(n² log n) time and O(n²) memory.

Related lab: Loops in motion