Find K-th Smallest Pair Distance (LeetCode 719): Solution and Explanation
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
- Sort
nums. Setlo = 0andhi = nums[n-1] - nums[0]. - While
lo < hi, takemid = (lo + hi) / 2. - Count pairs with distance
<= mid: for eachright, advanceleftwhilenums[right] - nums[left] > mid, then addright - left. - If the count is at least
k, sethi = mid; otherwise setlo = mid + 1. - Return
lo.
Step-by-step example
nums = [1,6,1], k = 3
- Sorted: [1,1,6]. The answer lies in [0, 5].
- mid = 2: the window counts the pair (1,1) only, so 1 pair < 3. Set lo = 3.
- mid = 4: still 1 pair, since 6 is 5 away from both ones. Set lo = 5.
- 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 lo1class Solution {
2 public int smallestDistancePair(int[] nums, int k) {
3 Arrays.sort(nums);
4 int lo = 0, hi = nums[nums.length - 1] - nums[0];
5 while (lo < hi) {
6 int mid = lo + (hi - lo) / 2;
7 int count = 0;
8 int left = 0;
9 for (int right = 0; right < nums.length; right++) {
10 while (nums[right] - nums[left] > mid) {
11 left++;
12 }
13 count += right - left;
14 }
15 if (count >= k) {
16 hi = mid;
17 } else {
18 lo = mid + 1;
19 }
20 }
21 return lo;
22 }
23}1class Solution {
2public:
3 int smallestDistancePair(vector<int>& nums, int k) {
4 sort(nums.begin(), nums.end());
5 int lo = 0, hi = nums.back() - nums[0];
6 while (lo < hi) {
7 int mid = lo + (hi - lo) / 2;
8 int count = 0;
9 int left = 0;
10 for (int right = 0; right < (int) nums.size(); right++) {
11 while (nums[right] - nums[left] > mid) {
12 left++;
13 }
14 count += right - left;
15 }
16 if (count >= k) {
17 hi = mid;
18 } else {
19 lo = mid + 1;
20 }
21 }
22 return lo;
23 }
24};Time and space complexity
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.
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
midwhen the count equals k. Several pairs can share the same distance, so keep shrinking withhi = midand returnloat the end. - Resetting
leftto 0 for everyright. That turns the counting pass into O(n^2) and times out. - Counting each pair twice by adding
right - left + 1or 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.