Find K Closest Elements

Find the k numbers closest to x in a sorted array by searching for where their window starts.

Given a sorted array of integers arr and two integers k and x, return the k numbers of arr that are closest to x, in ascending order. A number a is closer to x than a number b if |a - x| < |b - x|, or if both are equally far from x and a < b.

Example 1
Input: arr = [1, 2, 3, 4, 5], k = 4, x = 3
Output: [1, 2, 3, 4]
Explanation: 1 and 5 are both 2 away from 3, and the tie goes to the smaller number, 1.
Example 2
Input: arr = [1, 2, 3, 4, 5], k = 4, x = -1
Output: [1, 2, 3, 4]
Example 3
Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], k = 3, x = 7
Output: [6, 7, 8]
Solution

The Idea

Picture a street with nine houses, numbered 1 to 9 in a row. You live at number 7 and want to visit the three houses nearest to you. You would not walk the whole street to measure every house. You would look around your own door: 7 itself, then 6 and 8 on either side. That is Example 3, and its answer is [6, 7, 8].

Notice that the three nearest houses sit side by side. In a sorted array that is always so. If a number is among the k closest, every number between it and x is at least as close, so it belongs in the answer too. The answer is therefore a run of k neighbouring elements, called a window. In Example 3 the window [6, 7, 8] starts at index 5.

So the whole problem comes down to one number: where does the window start? A window of 3 in 9 numbers can start anywhere from index 0 to index 6, which is 9 - 3. That makes seven choices. How do we find the right one without measuring every window?

Compare two windows that start one place apart. The window starting at index 3 is [4, 5, 6], and the one starting at index 4 is [5, 6, 7]. They share 5 and 6. The only difference is a trade: the second window drops 4, the first element of the first window, and takes 7, the element just past the end of the first window. 4 is 3 away from x = 7, and 7 is 0 away. The trade brings the window closer, so the answer starts later than index 3.

As the start moves right, both numbers in this trade get bigger. The number being dropped comes nearer to x, or passes it, and the number being taken moves further right. So the trade only gets worse. Once it stops paying off at some start, it never pays off again at a later one.

That means the possible starts split into two groups: first the starts where the window should move right, then the starts where it should not. The answer is the first start of the second group. Finding such a boundary is the job of binary search: check the middle of the range, throw away the half that cannot hold the answer, and repeat. Look at the picture below, where mid is the start being checked, in the middle of the starts still left.

The array 1 to 9 with x = 7 and a window of 3. At mid = 3, the first element 4 is 3 away and 7 just past the window is 0 away, so start later. At mid = 5, 6 is 1 away and 9 is 2 away, so start at 5 or before. At mid = 4, 5 is 2 away and 8 is 1 away, so start later. The answer window starts at 5: 6, 7, 8.

In the row labelled mid = 3, the window is [4, 5, 6]. Its first element, 4, is 3 away from x, while 7, just past the end, is 0 away, so the window starts later. That leaves starts 4 to 6, and the middle one is 5. In the row labelled mid = 5, the first element 6 is 1 away and 9 is 2 away. Trading 6 for 9 would make things worse, so the start is 5 or before.

Only starts 4 and 5 are left. In the row labelled mid = 4, 5 is 2 away and 8 is 1 away, so the window starts later than 4, at 5. The answer row shows the window [6, 7, 8]. Three checks were enough to choose among seven starts.

So the solution joins two ideas. The answer is a window of k neighbours that can slide along the array, and binary search decides where it sits by comparing the window's first element with the element just past its end.

Solution Approach

Turning that idea into code means settling three things: which starts to search, how to write the trade as a test, and what to do with ties.

The range of starts

Why not simply measure how far every number is from x? Sorting all the numbers by their distance to x and keeping the first k works, but it takes O(n log n) steps for n numbers and ignores that the array is already sorted. Searching for the window's start is much cheaper.

Which starts are possible? The window needs k elements, so the last start that fits is arr.length - k. The search keeps two bounds: lo begins at 0 and hi at arr.length - k. Inside the search, lo is below hi, so the middle start mid is always below hi too. That keeps the element just past its window, arr[mid + k], inside the array.

Writing the trade as a test

How do we say "the first element is farther" in code? The test is x - arr[mid] > arr[mid + k] - x. The left side is how far arr[mid] lies below x, and the right side is how far arr[mid + k] lies above x. When x sits between the two numbers, both sides are plain distances.

The test also works when both numbers are on one side of x. If both are below x, the right side is negative, the test is true, and the window moves right, toward x. If both are above x, the left side is negative, the test is false, and the window stays where it is or moves left. Leaving out Math.abs is on purpose, as the output below shows.

A true test means the answer starts after mid, so lo becomes mid + 1. A false test means it starts at mid or before, so hi becomes mid. When the two bounds meet, they point at the start.

Ties

What if the two numbers in the trade are equally far from x? The test uses >, so a tie counts as false and the window does not move right. That keeps the smaller number, which is what the problem asks for. In Example 1, 1 and 5 are both 2 away from 3, and the answer keeps 1.

Optional: shrinking the window from both ends

Is there a way without binary search? Start with the whole array as the window. While it holds more than k numbers, drop whichever end is farther from x, and the right end on a tie. Each step removes one number, so this takes n - k steps. It is easy to get right, but binary search needs only about log2(n - k + 1) checks.

Java Solution

The method findClosestElements works in these steps:

  1. First, set lo to 0 and hi to arr.length - k, the first and last possible starts of the window.
  2. While lo is less than hi, take the middle start mid = lo + (hi - lo) / 2.
  3. Compare the window's first element, arr[mid], with the element just past its end, arr[mid + k], using x - arr[mid] > arr[mid + k] - x. If the test is true, set lo = mid + 1; otherwise set hi = mid.
  4. When lo and hi meet, lo is the start. Create the list result, copy arr[lo] to arr[lo + k - 1] into it with a for loop, and return it.

The main method runs the three examples, a tie between 1 and 3 with x = 2, a k as large as the whole array, and an array with repeated numbers below x.

Java
import java.util.ArrayList;
import java.util.List;

public class FindKClosestElements {

    public static List<Integer> findClosestElements(int[] arr, int k, int x) {
        int lo = 0;
        int hi = arr.length - k;              // the last start where k elements still fit
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            // compare the window's first element with the one just past its end
            if (x - arr[mid] > arr[mid + k] - x) {
                lo = mid + 1;                 // arr[mid] is farther: the window starts later
            } else {
                hi = mid;                     // the window starts at mid or before
            }
        }
        List<Integer> result = new ArrayList<>(k);
        for (int i = lo; i < lo + k; i++) {
            result.add(arr[i]);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(findClosestElements(new int[] {1, 2, 3, 4, 5}, 4, 3));
        System.out.println(findClosestElements(new int[] {1, 2, 3, 4, 5}, 4, -1));
        System.out.println(findClosestElements(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 7));
        System.out.println(findClosestElements(new int[] {1, 3}, 1, 2));
        System.out.println(findClosestElements(new int[] {1, 2, 3}, 3, 100));
        System.out.println(findClosestElements(new int[] {1, 1, 2, 2, 2, 2, 2, 3, 3}, 3, 3));
    }
}

Running it prints:

Output
[1, 2, 3, 4]
[1, 2, 3, 4]
[6, 7, 8]
[1]
[1, 2, 3]
[2, 3, 3]

Look at the second line. With x = -1, every number lies above x, so every test is false, only hi moves, and the window stays at index 0: [1, 2, 3, 4]. The third line, [6, 7, 8], is the search from the picture. On the fourth line, 1 and 3 are both 1 away from 2, and the tie keeps the smaller one, [1].

The fifth line asks for 3 numbers out of 3. hi starts at 0, the loop never runs, and the whole array comes back, even though 100 is far from all of it.

The last line, [2, 3, 3], shows why the test has no Math.abs. At the first check, mid is 3, and arr[3] and arr[6] are both 2, below x = 3. The test reads 1 > -1, which is true, so the window moves right toward the 3s. With Math.abs on both sides it reads 1 > 1, a false tie, and that version returns [2, 2, 2] for this input.

The original implementation, FindKClosestElements.java, is on GitHub.

Complexity

The work is the binary search over the possible starts, plus copying the window into the result.

  • Time: O(log(n - k) + k), because each check halves the n - k + 1 possible starts, and the for loop then copies the k numbers of the window.
  • Space: O(1) besides the result, because the search keeps only lo, hi and mid, and the returned list of k numbers is the output itself.

Searching for the first position where a test turns from true to false is covered in Binary Search Basics.