Find K-th Smallest Pair Distance

Binary search the distance; count pairs with distance at most mid using a sorted two-pointer sweep.

Hard
Time O(n log n + n log M) Space O(1)
LeetCode
4 min read
binary-search two-pointers parametric-search

Problem#

Given an integer array nums and integer k, return the k-th smallest distance among all pairs (i, j) where the distance is |nums[i] - nums[j]|.

Examples#

  • nums = [1,3,1], k = 10
  • nums = [1,1,1], k = 20
  • nums = [1,6,1], k = 35

Constraints#

  • n == nums.length, 2 <= n <= 10^4, 0 <= nums[i] <= 10^6.

Approach#

Sort first. The count of pairs with distance at most d is monotonic in d. Binary search d over [0, max - min]; for each d, use a two-pointer sweep to count pairs in O(n).

Solution#

Find K-th Smallest Pair Distance
class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size();
auto countLE = [&](int d) {
int cnt = 0, l = 0;
for (int r = 0; r < n; ++r) {
while (nums[r] - nums[l] > d) ++l;
cnt += r - l;
}
return cnt;
};
int lo = 0, hi = nums.back() - nums.front();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countLE(mid) < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
};

Editorial#

Sorting unlocks the two-pointer count: for each right index, the leftmost valid index moves monotonically. Binary searching the answer turns an O(n^2) enumeration into O(n log M). The lower-bound result is the smallest distance for which at least k pairs fit.

Complexity#

  • Time: O(n log n + n log M).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.