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 arrkxkarrxaxb|a - x| < |b - x|xa < b
Example 1
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
Output: [1, 2, 3, 4]
Example 3
Output: [6, 7, 8]
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 kxk
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
As the start moves right, both numbers in this trade get bigger. The number being dropped comes nearer to x
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
In the row labelled mid = 3, the window is [4, 5, 6]. Its first element, 4, is 3 away from x
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
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 xxk
Which starts are possible? The window needs karr.length - klohiarr.length - klohimidhiarr[mid + k]
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] - xarr[mid]xarr[mid + k]xx
The test also works when both numbers are on one side of xxxxMath.abs
A true test means the answer starts after midlomid + 1midhimid
Ties
What if the two numbers in the trade are equally far from x>
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 kx
Java Solution
The method findClosestElements
- First, set
to 0 andlo tohi , the first and last possible starts of the window.arr.length - k - While
is less thanlo , take the middle starthi .mid = lo + (hi - lo) / 2 - Compare the window's first element,
, with the element just past its end,arr[mid] , usingarr[mid + k] . If the test is true, setx - arr[mid] > arr[mid + k] - x ; otherwise setlo = mid + 1 .hi = mid - When
andlo meet,hi is the start. Create the listlo , copyresult toarr[lo] into it with aarr[lo + k - 1] loop, and return it.for
The mainxkx
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:
[1, 2, 3, 4]
[1, 2, 3, 4]
[6, 7, 8]
[1]
[1, 2, 3]
[2, 3, 3]
Look at the second line. With xxhi
The fifth line asks for 3 numbers out of 3. hi
The last line, [2, 3, 3], shows why the test has no Math.absmidarr[3]arr[6]xMath.abs
The original implementation,
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
loop then copies thefor numbers of the window.k - Space: O(1) besides the result, because the search keeps only
,lo andhi , and the returned list ofmid numbers is the output itself.k
Searching for the first position where a test turns from true to false is covered in