LeetCode #719 Hard

Find K-th Smallest Pair Distance

Find K-th Smallest Pair Distance is LeetCode 719 (Hard). The distance of a pair is the absolute difference of its two values. Given an integer array nums and an integer k, return the k-th smallest distance among all pairs nums[i], nums[j] with i < j.

  • With up to 10⁴ values there are about 5 × 10⁷ pairs, so listing and sorting every distance is too slow and uses too much memory.
  • Values lie between 0 and 10⁶, so every distance does too.
Constraints
  • n == nums.length
  • 2 <= n <= 10⁴
  • 0 <= nums[i] <= 10⁶
  • 1 <= k <= n * (n - 1) / 2
binary-searchtwo-pointerssorting
Open on LeetCode ↗
02

Intuition

Finding the k-th distance directly is hard. An easier question is: for a guessed distance d, how many pairs are at most d apart? That count never shrinks as d grows, so binary search over d finds the smallest guess whose count reaches k, and that guess is the answer.

The count is quick once the array is sorted. For each value, the partners within d to its left form one unbroken block, and the block's left edge only moves right as you go along the array. One sliding window counts every close pair in O(n).

How to spot this pattern

"K-th smallest" over a set far too big to list (pairs, sums, products, matrix cells), where you can count how many items are at most some value: binary search on the value and count.

03

Approach

Try it first

Before reading on, write a function that, given a distance d, counts the pairs at most d apart in a sorted array in O(n). Then ask how that count changes as d grows, and use it to find the k-th distance.

1

Sort the values

A pair's distance does not depend on where its values sit, so sorting changes no distance. It makes every value's close partners a single block directly to its left, which is what lets a window count them.

2

Count the pairs at most d apart

Keep a left edge i, starting at 0. For each j, move i right while nums[j] - nums[i] > d, then add j - i: the values from i to j - 1 all pair with nums[j]. i never moves back, so a full count is O(n).

3

Binary search the distance

Search d from 0 to nums[-1] - nums[0], the largest distance. If at least k pairs are within mid, the answer is mid or smaller, so hi = mid; otherwise it is bigger, so lo = mid + 1. Stop when lo == hi.

4

Why the result is a real distance

The search ends on the smallest d whose count reaches k, so fewer than k pairs are within d - 1. The pairs exactly d apart therefore exist and include the k-th smallest one, which makes d the answer, not just a bound.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def smallestDistancePair(self, nums: List[int], k: int) -> int:
▶6 nums.sort()
▶7 lo, hi = 0, nums[-1] - nums[0]
▶8 while lo < hi:
▶9 mid = (lo + hi) // 2
▶10 count = i = 0
▶11 for j in range(len(nums)):
▶12 while nums[j] - nums[i] > mid:
▶13 i += 1
▶14 count += j - i
▶15 if count >= k:
▶16 hi = mid
▶17 else:
▶18 lo = mid + 1
▶19 return lo
distance guesses0lo1234567hisorted values1348pairs within guess4countksorted; the answer is a distance from 0 to 7
sorted[1, 3, 4, 8]
lo0
hi7
Sorting moves values around but changes no pair's distance. The largest distance is 8 − 1 = 7, so the answer is one of the guesses 0 to 7. The search asks, for one guess at a time, how many pairs are at most that far apart.
distance guesses0lo123mid4567hisorted values1348pairs within guess04countkguess 3: how many pairs are at most 3 apart?
lo0
hi7
mid3
Try the middle guess, 3. If at least 4 pairs are within 3, the k-th smallest distance is 3 or less; if not, it is more.
distance guesses0lo123mid4567hisorted values1i3j48pairs within guess14countkpair 3 with 1: at most 3 apart → +1
j1
i0
count1
The values from i up to just before 3 are all within 3 of it, so 1 pair end at 3.
distance guesses0lo123mid4567hisorted values1i34j8pairs within guess34countkpair 4 with 1 and 3: at most 3 apart → +2
j2
i0
count3
The values from i up to just before 4 are all within 3 of it, so 2 pairs end at 4.
distance guesses0lo123mid4567hisorted values1348i jpairs within guess34countk8 is more than 3 from every value left of it → +0
j3
i3
count3
First the left edge i moves past 1, 3 and 4, which are more than 3 below 8. It never has to come back: later values are bigger, so those values are even further from them. No value left of 8 is close enough, so no pair ending at 8 counts.
distance guesses0lo123mid4567hisorted values1348pairs within guess3<4countkonly 3 within 3 → answer is more than 3
count3
k4
lo4
3 is less than 4, so even the 4-th smallest pair is more than 3 apart. Set lo to 4.
distance guesses01234lo5mid67hisorted values1348pairs within guess04countkguess 5: how many pairs are at most 5 apart?
lo4
hi7
mid5
Try the middle guess, 5. If at least 4 pairs are within 5, the k-th smallest distance is 5 or less; if not, it is more.
distance guesses01234lo5mid67hisorted values1i3j48pairs within guess14countkpair 3 with 1: at most 5 apart → +1
j1
i0
count1
The values from i up to just before 3 are all within 5 of it, so 1 pair end at 3.
distance guesses01234lo5mid67hisorted values1i34j8pairs within guess34countkpair 4 with 1 and 3: at most 5 apart → +2
j2
i0
count3
The values from i up to just before 4 are all within 5 of it, so 2 pairs end at 4.
distance guesses01234lo5mid67hisorted values13i48jpairs within guess54countkpair 8 with 3 and 4: at most 5 apart → +2
j3
i1
count5
First the left edge i moves past 1, which is more than 5 below 8. It never has to come back: later values are bigger, so that value is even further from them. The values from i up to just before 8 are all within 5 of it, so 2 pairs end at 8.
distance guesses01234lo5mid67hisorted values1348pairs within guess5≥4countk5 pairs within 5 → answer is 5 or less
count5
k4
hi5
5 is at least 4, so the 4-th smallest distance is no more than 5. Set hi to 5, keeping 5 because it may be the answer.
distance guesses01234lo mid5hi67sorted values1348pairs within guess04countkguess 4: how many pairs are at most 4 apart?
lo4
hi5
mid4
Try the middle guess, 4. If at least 4 pairs are within 4, the k-th smallest distance is 4 or less; if not, it is more.
distance guesses01234lo mid5hi67sorted values1i3j48pairs within guess14countkpair 3 with 1: at most 4 apart → +1
j1
i0
count1
The values from i up to just before 3 are all within 4 of it, so 1 pair end at 3.
distance guesses01234lo mid5hi67sorted values1i34j8pairs within guess34countkpair 4 with 1 and 3: at most 4 apart → +2
j2
i0
count3
The values from i up to just before 4 are all within 4 of it, so 2 pairs end at 4.
distance guesses01234lo mid5hi67sorted values134i8jpairs within guess44countkpair 8 with 4: at most 4 apart → +1
j3
i2
count4
First the left edge i moves past 1 and 3, which are more than 4 below 8. It never has to come back: later values are bigger, so those values are even further from them. The values from i up to just before 8 are all within 4 of it, so 1 pair end at 8.
distance guesses01234lo mid5hi67sorted values1348pairs within guess4≥4countk4 pairs within 4 → answer is 4 or less
count4
k4
hi4
4 is at least 4, so the 4-th smallest distance is no more than 4. Set hi to 4, keeping 4 because it may be the answer.
distance guesses01234lo hi567sorted values1348pairs within guess4countkone guess left → the answer is 4
lo = hi4
answer4
Only 4 is left. It is the smallest guess with at least 4 pairs within it, while 3 had fewer, so some pair is exactly 4 apart and it is the 4-th smallest. The answer is 4.
05

Common pitfalls

Counting pairs strictly closer than the guess

✗ Wrong
while i < j and nums[j] - nums[i] >= mid:
    i += 1
✓ Right
while nums[j] - nums[i] > mid:
    i += 1

This counts pairs less than mid apart, so the search lands one past the answer. On [1, 3, 1] with k = 1 the two 1s are 0 apart, yet it returns 1. With >, no guard is needed: nums[j] - nums[j] is 0, so i always stops at j.

Returning as soon as the count equals k

✗ Wrong
if count == k:
    return mid
✓ Right
if count >= k:
    hi = mid

Many guesses can give the same count, and most of them are not distances of any pair. On [1, 6, 1] with k = 1 the first guess is 2, which already has exactly one pair within it, so it returns 2 instead of 0.

06

Edge cases

Every value the same, e.g. [4, 4, 4]

The largest distance is 0, so lo and hi start equal, the loop never runs, and the answer is 0 for any k.

07

Complexity

Time
O(n log n + n log W)
Space
O(1) beyond the sort
W is the largest value minus the smallest, at most 10⁶, so about 20 guesses. Each guess is one O(n) window pass. Sorting costs O(n log n) and may use O(n) memory, depending on the language.
08

Find K-th Smallest Pair Distance FAQ

Why not use a min-heap of pairs?

Seed the heap with each value and its right neighbour, pop k times, and push the next pair from the popped one's left value. It is O((n + k) log n), fine for small k, but k can reach about 5 × 10⁷, and then it is far slower than the binary search.

Can I count with bisect or lower_bound instead of a window?

Yes. For each j, binary search for the first index whose value is at least nums[j] - d, then add j minus that index. It is easier to get right but costs O(n log n) per guess instead of O(n).

Where else does this count-and-search idea apply?

Anywhere the k-th smallest value comes from a set too large to list but easy to count against a guess. Kth Smallest Element in a Sorted Matrix uses the same search with a staircase count, and the k-th smallest product of two sorted arrays works the same way.