Find K Closest Elements (LeetCode 658): Solution and Explanation
Given a sorted array, a count k and a target x, return the k values closest to x, in ascending order. When two values are equally close, the smaller one wins.
Watch it run step by step
Try your own input and write the code →Intuition
A direct approach sorts the whole array by distance to x and takes the first k, then sorts those again by value. That is O(n log n) and ignores the fact that the array is already sorted.
The sorted order gives a stronger property: the answer is always a contiguous block of k elements. If some value were picked while a closer value between it and x was skipped, swapping them would improve the answer. So the real question is only where that window of length k starts, and the start can be anywhere from 0 to n - k.
Binary search on that start position. Suppose the window starts at mid, so it covers arr[mid] through arr[mid + k - 1]. Compare it with the window shifted one step right, which drops arr[mid] and adds arr[mid + k]. If x - arr[mid] is greater than arr[mid + k] - x, the left element is farther than the element just outside on the right, so the best window starts later and left = mid + 1. Otherwise the current start or something earlier is at least as good, so right = mid.
Notice the comparison uses signed differences rather than absolute values. That is deliberate: when both arr[mid] and arr[mid + k] are on the same side of x, the signed form still points the search in the right direction, and the strict greater than sign keeps ties on the left, matching the rule that smaller values win.
Approach: Binary search on the window start
- Set
left = 0andright = len(arr) - k, the range of possible starting indices. - While
left < right, computemid = (left + right) // 2. - If
x - arr[mid] > arr[mid + k] - x, the window should move right, so setleft = mid + 1. - Otherwise set
right = mid, keeping the current start as a candidate. - When the bounds meet, return the slice
arr[left:left + k], which is already sorted.
Step-by-step example
arr = [1,3,5,7,9,11], k = 2, x = 6
- The window can start anywhere from 0 to 4, so
left = 0andright = 4. mid = 2. Compare6 - 5 = 1witharr[4] - 6 = 3. 1 is not greater than 3, soright = 2.mid = 1. Compare6 - 3 = 3witharr[3] - 6 = 1. 3 is greater than 1, soleft = 2.- Now
left == right == 2, so the loop stops. - Return
arr[2:4], which is [5,7]. Both values are 1 away from 6, which is the best any pair can do.
Code: Python, Java, C++
1class Solution:
2 def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
3 left, right = 0, len(arr) - k
4
5 while left < right:
6 mid = (left + right) // 2
7 # Compare distance from x to left vs right of window
8 if x - arr[mid] > arr[mid + k] - x:
9 left = mid + 1
10 else:
11 right = mid
12
13 return arr[left:left + k]1class Solution {
2 public List<Integer> findClosestElements(int[] arr, int k, int x) {
3 int left = 0, right = arr.length - k;
4
5 while (left < right) {
6 int mid = (left + right) / 2;
7 if (x - arr[mid] > arr[mid + k] - x) {
8 left = mid + 1;
9 } else {
10 right = mid;
11 }
12 }
13
14 List<Integer> result = new ArrayList<>();
15 for (int i = left; i < left + k; i++) {
16 result.add(arr[i]);
17 }
18 return result;
19 }
20}1class Solution {
2public:
3 vector<int> findClosestElements(vector<int>& arr, int k, int x) {
4 int left = 0, right = arr.size() - k;
5
6 while (left < right) {
7 int mid = (left + right) / 2;
8 if (x - arr[mid] > arr[mid + k] - x) {
9 left = mid + 1;
10 } else {
11 right = mid;
12 }
13 }
14
15 return vector<int>(arr.begin() + left, arr.begin() + left + k);
16 }
17};Time and space complexity
O(log(n - k) + k)
The binary search runs over n - k + 1 candidate starts, taking O(log(n - k)) steps, and building the final slice copies k elements.
O(1)
Apart from the output slice, the search uses only a few integer variables.
Other approaches
Two pointers shrinking from both ends (time O(n - k), space O(1))
Start with the whole array and repeatedly drop whichever end is farther from x, preferring to drop the right end on ties, until k elements remain. It is easy to explain and needs no binary search reasoning.
Max heap by distance (time O(n log k), space O(k))
Push each element keyed by its distance to x (and value for ties) into a max heap capped at size k, then sort the survivors. It also works for unsorted input but wastes the sorted order here.
Common mistakes
- Setting
right = len(arr) - 1. The window must fit, so the last valid start islen(arr) - k, and a larger bound makesarr[mid + k]go out of range. - Comparing
abs(x - arr[mid])withabs(arr[mid + k] - x). When both values lie on the same side ofxand are equal, absolute values can send the search the wrong way, for example with duplicate values. - Using
>=instead of>. On a tie the smaller value should win, which means keeping the window to the left. - Returning the window without noting it is already sorted, then sorting it again, which is harmless but unnecessary.
Frequently asked questions
Why is the answer always a contiguous subarray?
The array is sorted, so values closer to x sit between x and values farther away. Any selection that skipped a closer value in favor of a farther one could be improved by swapping them, so the best k values form a single block.
Why compare arr[mid] with arr[mid + k]?
Those are the element that leaves and the element that enters when the window slides one step right. Whichever is closer to x tells you whether sliding right improves the window.
What is the time complexity of Find K Closest Elements?
The binary search is O(log(n - k)) and copying the result is O(k), for O(log(n - k) + k) overall. The two pointer version is O(n - k), and a heap is O(n log k).