Find K Closest Elements
Given a sorted integer array arr, an integer k, and an integer x, return the k closest integers to x in the array. The result should be sorted in ascending order. Closeness is measured by absolute difference |arr[i] - x|. If there is a tie, the smaller element is preferred.
A naive approach would sort by absolute difference and take the first k elements, requiring O(n log n) time. Binary search achieves O(log n + k) by first finding the optimal window start position. The window of size k is always contiguous — the k closest elements form a contiguous subarray in the sorted array.
The binary search checks candidate start positions. For a given mid, compare arr[mid] and arr[mid + k]: if x is closer to arr[mid] than to arr[mid + k], the window start should be earlier; otherwise, later. This works because the window start must be between index 0 and n - k, and the comparison tells us which side to search.
Edge cases include x smaller than all elements (return first k), x larger than all elements (return last k), k equal to array length (return the whole array), and ties where arr[mid] and arr[mid + k] are equally close to x.
The binary search comparison uses the property that the k closest elements form a contiguous window. By comparing arr[mid] against arr[mid+k] relative to x, we determine whether to shift the window left or right. This avoids having to sort by absolute difference, keeping the algorithm efficient.
Example Input & Output
Two 1s are closest.
Four closest to 3 are [1,2,3,4].
Three closest to 3 are [2,3,4].
Single element.
x < all, pick first k.
Algorithm Flow

Solution Approach
Binary search window start between 0 and n-k. Compare arr[mid] with arr[mid+k] relative to x. Return the k-length subarray.
Time O(log n + k), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] arr, int k, int x) {
int lo = 0, hi = arr.length - k;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (x - arr[mid] > arr[mid + k] - x) lo = mid + 1;
else hi = mid;
}
return Arrays.copyOfRange(arr, lo, lo + k);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
