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.
- n == nums.length
- 2 <= n <= 10⁴
- 0 <= nums[i] <= 10⁶
- 1 <= k <= n * (n - 1) / 2
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).
"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.
Approach
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.
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.
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).
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.
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.
Code in Python, C++ and Java
i up to just before 3 are all within 3 of it, so 1 pair end at 3.i up to just before 4 are all within 3 of it, so 2 pairs end at 4.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.lo to 4.i up to just before 3 are all within 5 of it, so 1 pair end at 3.i up to just before 4 are all within 5 of it, so 2 pairs end at 4.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.hi to 5, keeping 5 because it may be the answer.i up to just before 3 are all within 4 of it, so 1 pair end at 3.i up to just before 4 are all within 4 of it, so 2 pairs end at 4.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.hi to 4, keeping 4 because it may be the answer.i up to just before 1 are all within 1 of it, so 1 pair end at 1.i moves past 1 and 1, which are more than 1 below 3. It never has to come back: later values are bigger, so those values are even further from them. No value left of 3 is close enough, so no pair ending at 3 counts.hi to 1, keeping 1 because it may be the answer.i up to just before 1 are all within 0 of it, so 1 pair end at 1.i moves past 1 and 1, which are more than 0 below 3. It never has to come back: later values are bigger, so those values are even further from them. No value left of 3 is close enough, so no pair ending at 3 counts.hi to 0, keeping 0 because it may be the answer.i up to just before 1 are all within 2 of it, so 1 pair end at 1.i moves past 1 and 1, which are more than 2 below 6. It never has to come back: later values are bigger, so those values are even further from them. No value left of 6 is close enough, so no pair ending at 6 counts.lo to 3.i up to just before 1 are all within 4 of it, so 1 pair end at 1.i moves past 1 and 1, which are more than 4 below 6. It never has to come back: later values are bigger, so those values are even further from them. No value left of 6 is close enough, so no pair ending at 6 counts.lo to 5.Common pitfalls
Counting pairs strictly closer than the guess
while i < j and nums[j] - nums[i] >= mid:
i += 1while nums[j] - nums[i] > mid:
i += 1This 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
if count == k:
return midif count >= k:
hi = midMany 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.
Edge cases
[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.
Complexity
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.