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|, the larger one minus the smaller one. Given an array of integers nums and an integer k, take every pair of positions i < j and return the k-th smallest of all their distances. Equal distances count separately, and k is at least 1 and at most the number of pairs.

Example 1
Input: nums = [1, 3, 1], k = 1
Output: 0
Explanation: the pairs have distances 2, 0 and 2, and the smallest is 0.
Example 2
Input: nums = [1, 1, 1], k = 2
Output: 0
Explanation: all three pairs have distance 0, so the second smallest is 0 too.
Example 3
Input: nums = [1, 6, 1], k = 3
Output: 5
Explanation: the distances are 5, 0 and 5, so smallest first they read 0, 5, 5.
Solution

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.

For sorted nums 1, 3, 4, 8 the six distances, smallest first, are 1, 2, 3, 4, 5 and 7, and the 3rd smallest is 3. Below, the number of pairs within d for d from 0 to 7 is 0, 1, 2, 3, 4, 5, 5, 6. The first d with at least k = 3 pairs is 3.

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 the answer is 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 d and ask how many pairs are at most d apart. Call them the pairs within d. The bottom two rows of the picture, labelled "d" and "pairs within d", give that count for every d from 0 to 7.

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 right. The earlier numbers within d of it form an unbroken block that ends just before it, from some position left to right - 1. That block holds right - left pairs.

When right moves on to a bigger number, left can only move forward: a number too far from nums[right] is also too far from every bigger number. So both markers walk through the array once, and one pass counts every pair. Two markers that move the same way, with the stretch of numbers between them as the thing that counts, are called a sliding window.

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 moves past 1, 3 and 4, which are all more than 3 away, so 0 pairs. The total is 3, the count the picture shows under d = 3.

Keeping the right half

What do we do with a count? Keep the range as lo to hi and try its middle, mid. If at least k pairs are within mid, the answer is mid or smaller, so hi moves to mid. Otherwise the answer is bigger, so lo moves to mid + 1. The search stops when the two meet.

For 1, 3, 4, 8 and k = 3, the range starts as 0 to 7. The middle, 3, has 3 pairs, so hi becomes 3. Then 1 has 1 pair and 2 has 2 pairs, so lo becomes 2 and then 3. Now lo and hi are both 3, the answer.

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 int? The largest count an int can store is 2,147,483,647. The number of pairs, n(n - 1)/2, passes that once n is above 65,536, and 100,000 numbers have 4,999,950,000 pairs. The count is kept in a long, which holds far bigger values.

Java Solution

The method smallestDistancePair works in these steps:

  1. First, sort the input array with Arrays.sort(nums). This sorts the caller's array in place, so [10, 3, 1] becomes [1, 3, 10].
  2. Set lo to 0 and hi to the last number minus the first, the smallest and largest possible distances.
  3. While lo is below hi, take the middle distance mid and count the pairs within it with the helper pairsWithin.
  4. Inside pairsWithin, a loop moves right along the array. For each right, a second loop moves left forward while nums[right] - nums[left] is bigger than the limit. Then right - left is added to count, a long.
  5. Back in the search, if the count is at least k, set hi to mid. Otherwise set lo to mid + 1.
  6. When lo meets hi, return lo.

The main method runs the three examples and the picture's array with k = 3 and k = 6. Then it counts all the pairs among the numbers 0 to 99,999 and asks that array for its 2,000,000,000th smallest distance.

Java
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:

Output
0
0
5
3
7
4999950000
22541

The examples give 0, 0 and 5. In the third, [1, 6, 1] has the distances 0, 5 and 5, and k = 3 asks for the last of them, so 5 is right even though it appears twice. Next, [8, 1, 4, 3] gives 3, the 3rd smallest distance from the picture, and 7 for k = 6, the distance from 1 to 8.

The line 4999950000 is the number of pairs among 0 to 99,999, since every pair is within 99,999. It is more than twice what an int holds. The last line, 22541, is the answer for k = 2,000,000,000: 1,999,962,930 pairs are within 22,540 and 2,000,040,389 within 22,541. A version that counts in an int returns 99999 for the same input, because its counts wrap around to wrong values once they pass the int limit.

The >= k check matters too. A search that stops as soon as the count equals k exactly can stop on a distance no pair has. For [1, 3, 10] and k = 1, such a version tries 4 first, finds exactly one pair within it, and returns 4. The method above returns 2, the distance from 1 to 3.

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 pairsWithin moves right and left at most n times each.
  • Space: O(1) besides the sort. The search and the count keep only a few numbers, and Arrays.sort sorts the array in place, using at most O(log n) extra space inside the library.

The same idea of binary searching a value and counting what lies below it solves Kth Smallest Element in a Sorted Matrix.