Find K-th Smallest Pair Distance
Hard
Topics
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
Input: nums = [1,3,1], k = 1 Output: 0
Example 2
Input: nums = [1,1,1], k = 2 Output: 0
Example 3
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
- Sort the array.
- Binary search
dover[0, max - min]. - For each candidate, count pairs within
dusing the two-pointer sweep. - Move
hidown when the count reachesk, otherwise moveloup. - 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 1Complexity
- 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 isr - 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
loat 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 loimport java.util.*;
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
int lo = 0, hi = nums[n - 1] - nums[0];
while (lo < hi) {
int mid = (lo + hi) / 2;
int c = 0, l = 0;
for (int r = 0; r < n; r++) {
while (nums[r] - nums[l] > mid) l++;
c += r - l;
}
if (c >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int smallestDistancePair(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size();
int lo = 0, hi = nums[n - 1] - nums[0];
auto count = [&](int mid) -> int {
int c = 0, l = 0;
for (int r = 0; r < n; r++) {
while (nums[r] - nums[l] > mid) l++;
c += r - l;
}
return c;
};
while (lo < hi) {
int mid = (lo + hi) / 2;
if (count(mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
};/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/ var smallestDistancePair = function(nums, k) {
nums.sort((a, b) => a - b);
const n = nums.length;
let lo = 0, hi = nums[n - 1] - nums[0];
const count = (mid) => {
let c = 0, l = 0;
for (let r = 0; r < n; r++) {
while (nums[r] - nums[l] > mid) l++;
c += r - l;
}
return c;
};
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (count(mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
};