Problem 564
Kth Smallest Pair Distance
Hard · 30 pts · Array, Binary Search, Two Pointers, Sorting
Problem
The distance of a pair of positions i < j is |A[i] - A[j]|. Among all N × (N - 1) / 2 pairs, find the K-th smallest distance. Listing every pair is too slow for N = 10000. Sort the array and binary search on the answer d: with two pointers you can count in O(N) how many pairs have distance at most d, and the answer is the smallest d whose count is at least K.
Input
The first line contains N and K. The second line contains N integers.
Output
Print the K-th smallest pair distance.
Constraints
2 <= N <= 10000; 0 <= A[i] <= 1000000; 1 <= K <= N × (N - 1) / 2
Example input
3 1 1 3 1
Example output
0
Explanation
For 1 3 1 the pair distances are |1-3| = 2, |1-1| = 0 and |3-1| = 2. Sorted they are 0, 2, 2, so with K = 1 the answer is 0.