Find K-th Smallest Pair Distance (LeetCode 719): Solution and Explanation

Hard
Array
Two Pointers
Binary Search
Sorting

Given nums and k, return the k-th smallest value of |nums[i] - nums[j]| over all pairs i < j. For [1,3,1] and k = 1 the distances are 2, 0 and 2, so the answer is 0. With up to 10^4 values there are about 5 * 10^7 pairs, too many to list.

Intuition

Instead of finding the k-th distance directly, ask a yes or no question: are there at least k pairs with distance at most d? The answer flips from no to yes exactly once as d grows, so binary search finds the first d where it says yes.

That first d is the k-th smallest distance. With fewer than k pairs at d - 1 and at least k at d, the k-th distance in sorted order must equal d.

After sorting, the pairs ending at index right with distance at most d are exactly the indices in a window [left, right). As right moves forward, left only moves forward too, so one pass counts all pairs in O(n).

Approach: Binary search on the answer with a sliding window count

  1. Sort nums. Set lo = 0 and hi = nums[n-1] - nums[0].
  2. While lo < hi, take mid = (lo + hi) / 2.
  3. Count pairs with distance <= mid: for each right, advance left while nums[right] - nums[left] > mid, then add right - left.
  4. If the count is at least k, set hi = mid; otherwise set lo = mid + 1.
  5. Return lo.

Step-by-step example

nums = [1,6,1], k = 3
  1. Sorted: [1,1,6]. The answer lies in [0, 5].
  2. mid = 2: the window counts the pair (1,1) only, so 1 pair < 3. Set lo = 3.
  3. mid = 4: still 1 pair, since 6 is 5 away from both ones. Set lo = 5.
  4. lo = hi = 5, so the 3rd smallest distance is 5.

Code: Python, Java, C++

1class Solution:
2    def smallestDistancePair(self, nums: List[int], k: int) -> int:
3        nums.sort()
4        lo, hi = 0, nums[-1] - nums[0]
5        while lo < hi:
6            mid = (lo + hi) // 2
7            count = 0
8            left = 0
9            for right in range(len(nums)):
10                while nums[right] - nums[left] > mid:
11                    left += 1
12                count += right - left
13            if count >= k:
14                hi = mid
15            else:
16                lo = mid + 1
17        return lo
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n + n log W)

Sorting costs O(n log n). Each of the log W binary search rounds, where W = max - min, runs one O(n) window pass.

Space

O(1)

Only a few counters besides the space the sort uses.

Other approaches

Bucket count of distances (time O(n^2 + W), space O(W))

Since values are at most 10^6, count how many pairs have each exact distance with a frequency array and walk the buckets until k is reached. Building the buckets still takes O(n^2) time.

Heap of adjacent pairs (time O((n + k) log n), space O(n))

After sorting, push pairs (i, i+1) into a min-heap and pop k times, pushing (i, j+1) after each pop. It is the k-way merge idea and is slow when k is near n^2 / 2.

List every distance and sort (time O(n^2 log n), space O(n^2))

Correct and simple, but n^2 / 2 distances use too much time and memory for n = 10^4.

Common mistakes

  • Forgetting to sort first. The sliding window count only works on a sorted array.
  • Returning mid when the count equals k. Several pairs can share the same distance, so keep shrinking with hi = mid and return lo at the end.
  • Resetting left to 0 for every right. That turns the counting pass into O(n^2) and times out.
  • Counting each pair twice by adding right - left + 1 or counting both directions.

Frequently asked questions

Why is the answer guaranteed to be an actual pair distance?

The search returns the smallest d with count(d) >= k. If no pair had distance exactly d, then count(d - 1) would equal count(d), which contradicts d being the smallest.

Could the count overflow a 32-bit integer?

The count never exceeds n(n-1)/2, which is about 5 * 10^7 for n = 10^4, so a 32-bit int is enough.

How does this relate to other problems?

It is the same pattern as Kth Smallest Number in Multiplication Table and Kth Smallest Element in a Sorted Matrix: binary search a value and count how many items are at most that value.