Practice › Binary Search
Kth Smallest Pair Distance
Hard · Binary Search · Asked at Google, Amazon
The distance of a pair (a[i], a[j]) with i < j is |a[i] − a[j]|. Among all n(n − 1)/2 pairs, print the k-th smallest distance.
Input
First line: n k. Second line: n integers.
Output
The k-th smallest pair distance.
Constraints
- 2 ≤ n ≤ 10^4
- 1 ≤ k ≤ n(n − 1)/2
- 0 ≤ a[i] ≤ 10^6
Sort the array and binary search on the distance d. Count pairs with distance ≤ d using two pointers in O(n). The answer is the smallest d with count ≥ k. Counts can exceed 2^31 — use 64-bit integers.
Example 1
Input
3 1 1 3 1
Output
0
Example 2
Input
3 3 1 6 1
Output
5
Hints
- There are up to 5 × 10^7 pairs — too many to list.
- Binary search on the distance d instead.
- In a sorted array, pairs with distance ≤ d can be counted with two pointers in O(n).
Approach
Sort the array. For a candidate d, count pairs (j < i) with a[i] − a[j] ≤ d: move j forward while a[i] − a[j] > d, then add i − j. Binary search the smallest d in [0, max − min] with count ≥ k. The count can reach about 5 × 10^7 for n = 10^4, so it needs 64 bits in C++/Java to be safe.
Complexity: O(n log n + n log(max)) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
long long k;
cin >> n >> k;
vector<long long> a(n);
for (auto &x : a) cin >> x;
sort(a.begin(), a.end());
long long lo = 0, hi = a[n - 1] - a[0];
while (lo < hi) {
long long mid = (lo + hi) / 2, cnt = 0;
for (int i = 0, j = 0; i < n; i++) {
while (a[i] - a[j] > mid) j++;
cnt += i - j;
}
if (cnt >= k) hi = mid;
else lo = mid + 1;
}
cout << lo << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, k = data[0], data[1]
a = sorted(data[2 : 2 + n])
lo, hi = 0, a[-1] - a[0]
while lo < hi:
mid = (lo + hi) // 2
cnt = j = 0
for i in range(n):
while a[i] - a[j] > mid:
j += 1
cnt += i - j
if cnt >= k:
hi = mid
else:
lo = mid + 1
print(lo)Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
long k = (long) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
Arrays.sort(a);
long lo = 0, hi = a[n - 1] - a[0];
while (lo < hi) {
long mid = (lo + hi) / 2, cnt = 0;
for (int i = 0, j = 0; i < n; i++) {
while (a[i] - a[j] > mid) j++;
cnt += i - j;
}
if (cnt >= k) hi = mid;
else lo = mid + 1;
}
System.out.println(lo);
}
}Solve Kth Smallest Pair Distance online · All practice problems