Find K-th Smallest Pair Distance
Find the k-th smallest gap between two numbers of an array, without listing every pair.
The distance between two numbers a and b is |a - b|numski < jk
Example 1
Output: 0
Explanation: the pairs have distances 2, 0 and 2, and the smallest is 0.
Example 2
Output: 0
Explanation: all three pairs have distance 0, so the second smallest is 0 too.
Example 3
Output: 5
Explanation: the distances are 5, 0 and 5, so smallest first they read 0, 5, 5.
The Idea
Picture four houses along a street, at the numbers 1, 3, 4 and 8. Every two houses are some distance apart, and we want the third shortest of those distances. Four houses make six pairs, so we could simply measure all six. Look at the picture below.
The top row, labelled "sorted nums", holds the four numbers. The row below it lists the six distances, smallest first, with the two numbers of each pair underneath. The 3rd smallest is 3, the distance from 1 to 4, so for k = 3
Measuring every pair is fine for four numbers, but n numbers make n(n - 1)/2 pairs. For 10,000 numbers that is about 50 million distances to compute and sort. Can we find the k-th smallest without listing them all?
Turn the question around. Instead of asking for the 3rd smallest distance, pick a distance ddd
At d = 2 only two pairs are within 2: 4 and 3, and 3 and 1. Fewer than 3, so the 3rd smallest distance must be bigger than 2. At d = 3 the count reaches 3, so the 3rd smallest distance is at most 3. Together that pins the answer to 3: it is the first d whose count reaches k.
The count never goes down as d grows, because a pair within d is also within d + 1. So the question "are there at least k pairs within d?" answers no for every small d and yes from the answer onward. When the answers flip only once like that, we can find the flip by trying the middle of the range and keeping the half that still holds it. Trying the middle and keeping one half, again and again, is binary search, and here the halves are ranges of distances, not positions in the array.
Solution Approach
Turning that idea into code means settling four things: which distances to search, how to count the pairs within a distance quickly, which half to keep after each count, and how big the count can get.
The range of distances
Where does the search start and end? Once the array is sorted, the smallest possible distance is 0 and the largest is the last number minus the first. For 1, 3, 4, 8 that is the range 0 to 7. Each step halves the range, so even a range of a billion distances takes only about 30 steps.
Counting the pairs within a distance
How do we count the pairs within d without looking at every pair? Checking all pairs would cost about n²/2 steps for each count, no better than listing the distances. Sorting helps here too. Take the number at position rightleftright - 1right - left
When rightleftnums[right]
Try it for d = 3 on 1, 3, 4, 8. At 3, the block is just the 1, so 1 pair. At 4, the block is 1 and 3, so 2 pairs. At 8, left
Keeping the right half
What do we do with a count? Keep the range as lohimidmidmidhimidlomid + 1
For 1, 3, 4, 8 and k = 3, the range starts as 0 to 7. The middle, 3, has 3 pairs, so hilolohi
Can the search end on a d that no pair has? No. The count only rises at a distance some pair really has, and stays flat in between, as it does from d = 5 to d = 6 in the picture. The first d whose count reaches k is therefore always the distance of a real pair.
How big the count gets
Does the count fit in an intintlong
Java Solution
The method smallestDistancePair
- First, sort the input array with
. This sorts the caller's array in place, soArrays.sort(nums) becomes[10, 3, 1] .[1, 3, 10] - Set
to 0 andlo to the last number minus the first, the smallest and largest possible distances.hi - While
is belowlo , take the middle distancehi and count the pairs within it with the helpermid .pairsWithin - Inside
, a loop movespairsWithin along the array. For eachright , a second loop movesright forward whileleft is bigger than the limit. Thennums[right] - nums[left] is added toright - left , acount .long - Back in the search, if the count is at least
, setk tohi . Otherwise setmid tolo .mid + 1 - When
meetslo , returnhi .lo
The main
import java.util.Arrays;
public class KthSmallestPairDistance {
public static int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int lo = 0; // smallest possible distance
int hi = nums[nums.length - 1] - nums[0]; // largest possible distance
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (pairsWithin(nums, mid) >= k) {
hi = mid; // at least k pairs within mid: the answer is mid or less
} else {
lo = mid + 1; // fewer than k pairs: the answer is bigger than mid
}
}
return lo;
}
// Number of pairs i < j with nums[j] - nums[i] <= limit, in one pass over sorted nums
static long pairsWithin(int[] nums, int limit) {
long count = 0;
int left = 0;
for (int right = 0; right < nums.length; right++) {
while (nums[right] - nums[left] > limit) {
left++; // too far from nums[right], and from every later value
}
count += right - left; // nums[right] pairs with every index from left to right - 1
}
return count;
}
public static void main(String[] args) {
System.out.println(smallestDistancePair(new int[] {1, 3, 1}, 1));
System.out.println(smallestDistancePair(new int[] {1, 1, 1}, 2));
System.out.println(smallestDistancePair(new int[] {1, 6, 1}, 3));
System.out.println(smallestDistancePair(new int[] {8, 1, 4, 3}, 3));
System.out.println(smallestDistancePair(new int[] {8, 1, 4, 3}, 6));
int[] big = new int[100000];
for (int i = 0; i < big.length; i++) {
big[i] = i;
}
System.out.println(pairsWithin(big, 99999));
System.out.println(smallestDistancePair(big, 2000000000));
}
}
Running it prints:
0
0
5
3
7
4999950000
22541
The examples give 0, 0 and 5. In the third, [1, 6, 1][8, 1, 4, 3]
The line 4999950000intintint
The >= k[1, 3, 10]
Complexity
The work is the sort, plus one counting pass for every step of the binary search.
- Time: O(n log n + n log W), where W is the largest number minus the smallest. Sorting costs O(n log n). The search over 0 to W takes about log W steps, and in each one
movespairsWithin andright at most n times each.left - Space: O(1) besides the sort. The search and the count keep only a few numbers, and
sorts the array in place, using at most O(log n) extra space inside the library.Arrays.sort
The same idea of binary searching a value and counting what lies below it solves