15% off all plans & roadmaps Use code
See plansFind K Closest Elements
- LeetCode 658
- Medium
- Binary Search Patterns
- Find First/Last Occurrence
Updated
TL;DR: Return the k values nearest to x, in sorted order. The answer is always one contiguous window, so binary search for where that window starts.
Problem
You are given a sorted integer array arr, along with two integers k and x. Return the k integers in arr that are closest to x. The result must be sorted in ascending order.
An integer a is closer to x than an integer b when |a - x| < |b - x|, or when |a - x| == |b - x| and a < b.
Example 1
Input: arr = [1,2,3,4,5], k = 4, x = 3 Output: [1,2,3,4]
Example 2
Input: arr = [1,1,2,3,4,5], k = 4, x = -1 Output: [1,1,2,3]
Constraints
1 <= k <= arr.length1 <= arr.length <= 10^4arris sorted in ascending order.-10^4 <= arr[i], x <= 10^4
Constraints that matter
- n up to 10^4 makes O(n log n) sorting fast enough to pass, but the sorted input lets you do better.
- Because the input is sorted, the answer is a contiguous window of length k, so you only need to pick its start.
- Values can be negative and x can lie outside the array, so the window logic must handle x below every value or above every value.
- Ties must favor the smaller value, which fixes the direction of every comparison in the search.
Hints
Hint 1
The array is sorted, so the k closest values form one contiguous block.
Hint 2
Sort every value by its distance to x, breaking ties by value.
Solution
Intuition
The array is sorted, so the k closest values form one contiguous block. Pick any value in the answer. Every value between it and x is strictly closer to x, so it must be in the answer too. The job reduces to finding where the block starts.
Picture a fixed-width frame laid over a row of sorted fence posts, with a pole planted at x. The frame is the window, and sliding it one notch right swaps the leftmost post for the next post on the right.
A block of size k that starts at index i covers arr[i] through arr[i + k - 1]. The start i can be any index from 0 to n - k, so there are n - k + 1 candidates. You do not need to score each candidate. You only need to compare neighbors.
Compare window i with window i + 1. They share k - 1 values. The only change is that arr[i] leaves and arr[i + k] enters. Whether the window should move right depends only on those two numbers.
The answer changes from yes to no only once as i grows. So this is a binary search for a boundary, the Find First/Last Occurrence subpattern.
If x - arr[i] > arr[i + k] - x, the entering value is strictly closer to x, so the window moves right. Otherwise the window stays or moves left. Ties keep the left window, which matches the rule that prefers the smaller value.
Worked example
Input: arr = [1,2,3,4,5], k = 4, x = 3 Output: [1,2,3,4] Explanation: The value 3 is the closest, then 2 and 4 are tied at distance 1, and 1 and 5 are tied at distance 2. The tie goes to the smaller value, so 1 wins over 5. Keeping the four closest values gives 1, 2, 3, 4, which is already sorted.
Approach 1: Brute force: sort by distance
Sort every value by its distance to x, breaking ties by value. Keep the first k values from that ranking. The output must be ascending, so sort those k values once more.
This ignores the sorted input completely. It is still correct, and it gives you a baseline that the next two approaches improve.
Steps
- Copy arr and sort the copy by the key (distance to x, then value).
- Take the first k values of the sorted copy.
- Sort those k values in ascending order.
- Return them.
Dry run
Distances from 3 to the values 1 through 5 are 2, 1, 0, 1, 2. Sorted by distance and then by value, the order is 3, 2, 4, 1, 5. The first four are 3, 2, 4, 1. Sorting them ascending gives [1,2,3,4], which matches the expected output.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Let n be the length of arr. A comparison sort on n values takes O(n log n) comparisons. That dominates copying the array and sorting the k picks, which cost O(n) and O(k log k). Since k is at most n, the total is O(n log n). The sorted copy needs O(n) extra space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Rank every value by distance to x, then by value
ranked = sorted(arr, key=lambda v: (abs(v - x), v))
# The output must be ascending, so sort the k picks
return sorted(ranked[:k])JavaTested in our runner
import java.util.*;
class Solution {
public int[] findClosestElements(int[] arr, int k, int x) {
// Box the values so we can sort with a custom comparator
Integer[] ranked = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) {
ranked[i] = arr[i];
}
Arrays.sort(ranked, (a, b) -> {
int da = Math.abs(a - x);
int db = Math.abs(b - x);
return da == db ? a - b : da - db;
});
// Copy the k closest and sort them ascending
int[] res = new int[k];
for (int i = 0; i < k; i++) {
res[i] = ranked[i];
}
Arrays.sort(res);
return res;
}
}C++Tested in our runner
#include <algorithm>
#include <cstdlib>
using namespace std;
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
// Rank a copy of arr by distance to x, then by value
vector<int> ranked = arr;
sort(ranked.begin(), ranked.end(), [x](int a, int b) {
int da = abs(a - x);
int db = abs(b - x);
if (da == db) return a < b;
return da < db;
});
// Keep the k closest and sort them ascending
vector<int> res(ranked.begin(), ranked.begin() + k);
sort(res.begin(), res.end());
return res;
}
};JavaScriptTested in our runner
var findClosestElements = function(arr, k, x) {
// Rank a copy of arr by distance to x, then by value
const ranked = [...arr].sort((a, b) => (Math.abs(a - x) - Math.abs(b - x)) || (a - b));
// Keep the k closest and sort them ascending
return ranked.slice(0, k).sort((a, b) => a - b);
};GoTested in our runner
import "sort"
func findClosestElements(arr []int, k int, x int) []int {
dist := func(v int) int {
if v < x {
return x - v
}
return v - x
}
// Rank a copy of arr by distance to x, then by value
ranked := make([]int, len(arr))
copy(ranked, arr)
sort.Slice(ranked, func(i, j int) bool {
di, dj := dist(ranked[i]), dist(ranked[j])
if di == dj {
return ranked[i] < ranked[j]
}
return di < dj
})
// Keep the k closest and sort them ascending
res := make([]int, k)
copy(res, ranked[:k])
sort.Ints(res)
return res
}C#Tested in our runner
public class Solution {
public int[] findClosestElements(int[] arr, int k, int x) {
// Rank by distance to x, then by value
var ranked = arr.OrderBy(v => Math.Abs(v - x)).ThenBy(v => v).ToArray();
// Keep the k closest and sort them ascending
return ranked.Take(k).OrderBy(v => v).ToArray();
}
}Approach 2: Two pointers outward from x
What's slow: the brute force sorts all n values, even though only k are needed and the array is already sorted. The insight that fixes it: in a sorted array, the values on each side of x already appear in order of distance. Binary search finds the split point around x, and then you walk outward.
At each step, you take the closer of the two neighbors. That is one comparison and one move, so the walk costs O(1) per value taken.
Steps
- Binary search for r, the first index with
arr[r] >= x. - Set l = r - 1. Everything at or left of l is below x, and everything at or right of r is at least x.
- While the open window (l, r) holds fewer than k values, compare
x - arr[l]witharr[r] - x. - If the left value is at least as close, move l left by one. Otherwise move r right by one.
- If one side has run out of values, take the other side.
- Return arr[l+1 .. r-1].
Dry run
Binary search gives r = 2, since arr[2] = 3 is the first value at or above 3. Set l = 1. The window (1, 2) is empty, and it needs 4 values.
Step 1: arr[1] = 2 is at distance 1, and arr[2] = 3 is at distance 0. The right side is closer, so r = 3. The window (1, 3) now holds 3.
Step 2: arr[1] = 2 and arr[3] = 4 are both at distance 1. The tie goes left, so l = 0. The window (0, 3) holds 2 and 3.
Step 3: arr[0] = 1 is at distance 2, and arr[3] = 4 is at distance 1. The right side is closer, so r = 4. The window (0, 4) holds 2, 3, 4.
Step 4: arr[0] = 1 and arr[4] = 5 are both at distance 2. The tie goes left, so l = -1. The window (-1, 4) holds 1, 2, 3, 4. Return [1,2,3,4].
Complexity
| Time | O(log n + k) |
|---|---|
| Space | O(1) extra |
Let n be the length of arr. The binary search does O(log n) comparisons. The walk runs exactly k times, because each iteration adds one value to the window and does constant work.
Copying the answer costs O(k), so the total time is O(log n + k). Only a few indices are stored, so the extra space is O(1).
PythonTested in our runner
import bisect
from typing import List, Optional
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Index of the first value >= x; the pointers surround it
right = bisect.bisect_left(arr, x)
left = right - 1
# The open window (left, right) grows by one value per iteration
while right - left - 1 < k:
if left < 0:
right += 1
elif right >= len(arr):
left -= 1
elif x - arr[left] <= arr[right] - x:
left -= 1
else:
right += 1
return arr[left + 1:right]JavaTested in our runner
import java.util.*;
class Solution {
public int[] findClosestElements(int[] arr, int k, int x) {
// Lower bound: first index whose value is >= x
int lo = 0;
int hi = arr.length;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (arr[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
int right = lo;
int left = right - 1;
// The open window (left, right) grows by one value per iteration
while (right - left - 1 < k) {
if (left < 0) {
right++;
} else if (right >= arr.length) {
left--;
} else if (x - arr[left] <= arr[right] - x) {
left--;
} else {
right++;
}
}
int[] res = new int[k];
for (int i = 0; i < k; i++) {
res[i] = arr[left + 1 + i];
}
return res;
}
}C++Tested in our runner
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int n = arr.size();
// First index whose value is >= x
int right = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
int left = right - 1;
// The open window (left, right) grows by one value per iteration
while (right - left - 1 < k) {
if (left < 0) {
right++;
} else if (right >= n) {
left--;
} else if (x - arr[left] <= arr[right] - x) {
left--;
} else {
right++;
}
}
return vector<int>(arr.begin() + left + 1, arr.begin() + right);
}
};JavaScriptTested in our runner
var findClosestElements = function(arr, k, x) {
// Lower bound: first index whose value is >= x
let lo = 0;
let hi = arr.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
let right = lo;
let left = right - 1;
// The open window (left, right) grows by one value per iteration
while (right - left - 1 < k) {
if (left < 0) {
right++;
} else if (right >= arr.length) {
left--;
} else if (x - arr[left] <= arr[right] - x) {
left--;
} else {
right++;
}
}
return arr.slice(left + 1, right);
};GoTested in our runner
func findClosestElements(arr []int, k int, x int) []int {
// Lower bound: first index whose value is >= x
lo, hi := 0, len(arr)
for lo < hi {
mid := lo + (hi-lo)/2
if arr[mid] < x {
lo = mid + 1
} else {
hi = mid
}
}
right := lo
left := right - 1
// The open window (left, right) grows by one value per iteration
for right-left-1 < k {
if left < 0 {
right++
} else if right >= len(arr) {
left--
} else if x-arr[left] <= arr[right]-x {
left--
} else {
right++
}
}
res := make([]int, k)
copy(res, arr[left+1:right])
return res
}C#Tested in our runner
public class Solution {
public int[] findClosestElements(int[] arr, int k, int x) {
// Lower bound: first index whose value is >= x
int lo = 0;
int hi = arr.Length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
int right = lo;
int left = right - 1;
// The open window (left, right) grows by one value per iteration
while (right - left - 1 < k) {
if (left < 0) {
right++;
} else if (right >= arr.Length) {
left--;
} else if (x - arr[left] <= arr[right] - x) {
left--;
} else {
right++;
}
}
int[] res = new int[k];
Array.Copy(arr, left + 1, res, 0, k);
return res;
}
}The Find First/Last Occurrence infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Find First/Last Occurrence
Part of Binary Search Patterns
Approach 3: Binary search for the window startOptimalFind First/Last Occurrence
What's slow: the walk takes k steps, and each step decides one value. The insight that fixes it: you never need to choose values one at a time. The only unknown is where the window starts.
Compare window i with window i + 1 using only two values, arr[i] and arr[i + k]. If the entering value is strictly closer to x, the window moves right. Otherwise it stays or moves left. Binary search on the start index needs only O(log(n - k)) of these checks.
Steps
- Set left = 0 and right = n - k, the range of valid window starts.
- While left < right, set mid = left + (right - left) / 2.
- If
x - arr[mid] > arr[mid + k] - x, the entering value is strictly closer, so set left = mid + 1. - Otherwise set right = mid, which keeps the left window on ties.
- When left == right, return the k values from arr[left] to arr[left + k - 1].
Dry run
| Step | left | right | mid | x - arr[mid] | arr[mid+k] - x | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 1 | - | - | - | Start with n - k = 1 |
| 2 | 0 | 1 | 0 | 3 - 1 = 2 | 5 - 3 = 2 | 2 > 2 is false, so right = 0 |
| 3 | 0 | 0 | - | - | - | left == right, stop |
Return arr[0 .. 3], which is [1,2,3,4].
Complexity
| Time | O(log(n - k) + k) |
|---|---|
| Space | O(1) extra |
Let n be the length of arr. The search range starts with n - k + 1 window starts, and each pass halves that range, so there are about log2(n - k + 1) passes. Each pass does constant work. Copying the k answer values adds O(k), so the total is O(log(n - k) + k), and the search alone is O(log(n - k)).
PythonTested in our runner
from typing import List, Optional
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Search for the start of the length-k window
left = 0
right = len(arr) - k
while left < right:
mid = left + (right - left) // 2
# Shift right only if arr[mid + k] is strictly closer than arr[mid]
if x - arr[mid] > arr[mid + k] - x:
left = mid + 1
else:
right = mid
return arr[left:left + k]JavaTested in our runner
import java.util.*;
class Solution {
public int[] findClosestElements(int[] arr, int k, int x) {
int left = 0;
int right = arr.length - k;
while (left < right) {
int mid = left + (right - left) / 2;
// Shift right only if arr[mid + k] is strictly closer than arr[mid]
if (x - arr[mid] > arr[mid + k] - x) {
left = mid + 1;
} else {
right = mid;
}
}
int[] res = new int[k];
for (int i = 0; i < k; i++) {
res[i] = arr[left + i];
}
return res;
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int left = 0;
int right = arr.size() - k;
while (left < right) {
int mid = left + (right - left) / 2;
// Shift right only if arr[mid + k] is strictly closer than arr[mid]
if (x - arr[mid] > arr[mid + k] - x) {
left = mid + 1;
} else {
right = mid;
}
}
return vector<int>(arr.begin() + left, arr.begin() + left + k);
}
};JavaScriptTested in our runner
var findClosestElements = function(arr, k, x) {
let left = 0;
let right = arr.length - k;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
// Shift right only if arr[mid + k] is strictly closer than arr[mid]
if (x - arr[mid] > arr[mid + k] - x) {
left = mid + 1;
} else {
right = mid;
}
}
return arr.slice(left, left + k);
};GoTested in our runner
func findClosestElements(arr []int, k int, x int) []int {
left, right := 0, len(arr)-k
for left < right {
mid := left + (right-left)/2
// Shift right only if arr[mid+k] is strictly closer than arr[mid]
if x-arr[mid] > arr[mid+k]-x {
left = mid + 1
} else {
right = mid
}
}
res := make([]int, k)
copy(res, arr[left:left+k])
return res
}C#Tested in our runner
public class Solution {
public int[] findClosestElements(int[] arr, int k, int x) {
int left = 0;
int right = arr.Length - k;
while (left < right) {
int mid = left + (right - left) / 2;
// Shift right only if arr[mid + k] is strictly closer than arr[mid]
if (x - arr[mid] > arr[mid + k] - x) {
left = mid + 1;
} else {
right = mid;
}
}
int[] res = new int[k];
Array.Copy(arr, left, res, 0, k);
return res;
}
}Common mistakes
- Setting
right = arr.lengthfor the window start. The last valid start is n - k, soarr[mid + k]reads past the end whenrightis too large. Useright = arr.length - k. - Writing
left = midinstead ofleft = mid + 1. When left and right differ by one,midequalsleft, and the loop never ends. Move past mid whenever you move left up. - Using
>=in the window comparison. On a tie, the window must stay left so the smaller value wins. Use strict>so that ties keep the left window. - In the two-pointer version, testing
x - arr[left] < arr[right] - x. That picks the right value on a tie, which breaks the rule that prefers the smaller value. Use<=for the left side. - Returning the k picks in ranking order from the brute force. The ranking is by distance, so the output can be out of order. Sort the k values ascending before returning them.
Edge cases
- k equals arr.length. The window start range is only 0, so the whole array comes back.
- x is below every value, such as arr = [5,6,7], k = 2, x = 0. The answer is [5,6], and the two-pointer walk takes the right side every step.
- x is above every value, such as arr = [1,2,3], k = 2, x = 10. The answer is [2,3].
- Duplicates equal to x, such as arr = [2,2,2,3], k = 2, x = 2. The answer is [2,2], since both are at distance 0.
- A tie across x, such as arr = [1,3], k = 1, x = 2. Both values are at distance 1, so the answer is [1].
Follow-ups interviewers ask
- What if the array is not sorted?
- Sort it first in O(n log n), then apply the binary search. If you cannot afford the full sort, keep a max-heap of size k ordered by distance and then value. That costs O(n log k) and uses O(k) extra space.
- Can you do it in O(1) extra space?
- Yes. The binary search and the two-pointer walk both keep only a few integer indices. The output array is required, and it is not counted as auxiliary space.
- What if the array does not fit in memory?
- The binary search only reads arr[mid] and arr[mid + k] at each probe. If the sorted data sits on disk, you can seek to byte offsets and read those two values. That takes O(log n) reads, and then you stream the k values from the window start.
Find K Closest Elements FAQ
What is the time complexity of Find K Closest Elements?
The binary search solution runs in O(log(n - k) + k) time, where n is the array length. The search takes O(log(n - k)) steps, and copying the answer takes O(k). The sorting approach takes O(n log n).
Why use binary search for Find K Closest Elements?
The answer is a contiguous window, so the problem reduces to finding its start index. Each comparison at the midpoint shows which half can hold the start, so half the candidates go away on every check.
Can Find K Closest Elements be solved in O(1) extra space?
Yes, the binary search and two-pointer solutions both use a fixed number of integer variables. The sorting approach needs O(n) for its ranked copy. The returned array is not counted in extra space.
Does the tie rule change the answer?
Yes. When two values are equally far from x, the smaller one must be chosen. That is why the comparison uses strict > and keeps the left window on ties.
Why does the window search compare only two values?
Windows i and i + 1 share k - 1 values. The only difference is that arr[i] leaves and arr[i + k] enters, so comparing those two decides the direction.
Asked at
See which companies ask this — Pro
Related problems
- Find First and Last Position of Element in Sorted Array · same technique: Find First/Last Occurrence
- Median of Two Sorted Arrays · next harder, same pattern
- Koko Eating Bananas · same pattern: Binary Search Patterns
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Capacity To Ship Packages Within D Days · same pattern: Binary Search Patterns
- Search in Rotated Sorted Array II · same pattern: Binary Search Patterns
- Find Peak Element · same pattern: Binary Search Patterns
- Peak Index in a Mountain Array · same pattern: Binary Search Patterns