Find K-th Smallest Pair Distance

Hard

Topics
ArrayTwo PointersBinary SearchSorting

The distance of a pair (a, b) is |a - b|. Given an integer array nums and an integer k, return the k-th smallest distance among all n * (n - 1) / 2 pairs (1-indexed).

Example 1

103112
Input:  nums = [1,3,1], k = 1
Output: 0

Example 2

101112
Input:  nums = [1,1,1], k = 2
Output: 0

Example 3

106112
Input:  nums = [1,6,1], k = 3
Output: 5

Constraints

  • 2 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^6
  • 1 <= k <= n * (n - 1) / 2
Editorial — intuition, approach, complexity and pitfalls

Intuition

There are up to about 5×10⁷ pairs at the stated bound, so the distances can never be materialised, let alone sorted. Instead binary search the answer: guess a distance d and count how many pairs are at most that far apart. That count is non-decreasing in d, so the smallest d whose count reaches k is the k-th smallest distance.

Counting is the pretty part. Sort the array first; then for each right end, slide a left pointer forward while the span exceeds d. Every index between the two pointers forms a valid pair with the right end, so r - l pairs are added without enumerating any of them. The left pointer only ever moves forward, so the count is O(n).

Approach

  1. Sort the array.
  2. Binary search d over [0, max - min].
  3. For each candidate, count pairs within d using the two-pointer sweep.
  4. Move hi down when the count reaches k, otherwise move lo up.
  5. Return the converged bound.

Dry Run

nums = [1,3,1]   k = 1

sorted [1,1,3]    all pair distances are [0, 2, 2]

  lo  hi  mid  pairs with distance <= mid  >= k
  0   2   1    1                           yes -- try smaller
  0   1   0    1                           yes -- try smaller

answer 0

the counting sweep at d = 1 on [1,1,3]
  r=0  l=0  adds 0
  r=1  l=0  adds 1   (the pair of 1s)
  r=2  l=2  adds 0   (3 - 1 > 1, so l advances past both 1s)
  total 1

Complexity

  • Time — O(n log n + n log(max)): the sort, plus one O(n) counting sweep per binary search step over a value range bounded by the largest gap. Measured: 10⁴ elements with k = 10⁷ in 0.04s, never building a pair.
  • Space — O(log n) in Java and C++ and O(n) in Python, all of it the sort's working memory. The algorithm itself adds only two pointers.

Common Pitfalls

  • Generating and sorting the distances. At 5×10⁷ pairs that exhausts memory before it exhausts time.
  • Binary searching without sorting first. The two-pointer count depends on order; unsorted input makes the sweep meaningless.
  • Counting with r - l + 1. The pair (r, r) is not a pair, so the count for a right end is r - l.
  • Resetting the left pointer inside the loop over r, which turns the O(n) sweep into O(n²) and the whole solution into O(n² log max).
  • Starting lo at 1. Duplicate values give a distance of 0, which is a legal answer — as the dry run shows.
  • Using a max-heap of size k. That is O(pairs log k), and the pair count is the thing that has to be avoided.

Full Solution — all languages

class Solution:
    def smallestDistancePair(self, nums, k):
        nums.sort()
        n = len(nums)
        lo, hi = 0, nums[-1] - nums[0]
        def count(mid):
            c = 0
            l = 0
            for r in range(n):
                while nums[r] - nums[l] > mid:
                    l += 1
                c += r - l
            return c
        while lo < hi:
            mid = (lo + hi) // 2
            if count(mid) >= k:
                hi = mid
            else:
                lo = mid + 1
        return lo
SensAI
Beta
Tap the mic to stop voice mode