Find K Closest Elements in Sorted Array
Heaps, Sorting & SearchAuto-graded · 26 test casesLast updated
Tests binary search on sorted arrays to locate a contiguous window of k elements with minimum distance to a target value.
Given a sorted array of integers arr, a positive integer k, and a target value x, find the k integers in arr that have the smallest absolute distance to x. Return them in ascending order.
Distance and Tie-Breaking
An element a is considered closer to x than element b if:
|a - x| < |b - x|, or|a - x| == |b - x|anda < b
In other words, when two elements are equidistant from the target, prefer the smaller element.
Important Details
- The array may contain duplicate values. Each occurrence is treated as a distinct element that can be included in the result.
- The target
xdoes not need to exist in the array and may fall outside the array's range. - Your output must be sorted in ascending order.
Constraints
1 <= k <= arr.length <= 10^4arris sorted in non-decreasing order-10^4 <= arr[i], x <= 10^4
Examples
Example 1
Input: closest_k_elements([1, 3, 4, 7, 9], 2, 5)
Output: [3, 4]
Example 2
Input: closest_k_elements([2, 4, 6, 8], 3, 10)
Output: [4, 6, 8]
Example 3
Input: closest_k_elements([-3, -1, -1, 2, 5], 3, 0)
Output: [-1, -1, 2]
Hints
Hint 1
The result will always be a contiguous slice of the sorted array. Why can't the closest k elements be scattered?
Hint 2
Use binary search to find the optimal starting position for a window of size k. What comparison determines whether to shift the window left or right?
Hint 3
When comparing arr[i] and arr[i+k] as candidates for the window boundary, use signed differences (x - arr[i]) vs (arr[i+k] - x) rather than absolute values to handle duplicates correctly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that the k closest elements must form a contiguous subarray of length k in the sorted array. This is because if we select an element at some position, any element between it and the target must be at least as close (or would be selected first due to the tie-breaking rule).
This reduces the problem to finding the optimal starting index i for a window [i, i+k) where 0 <= i <= n - k.
We use binary search to find this starting position. For any candidate position mid, we compare:
- The leftmost element we would include:
arr[mid] - The element just past the right end:
arr[mid + k]
If we shift the window one position right, we drop arr[mid] and add arr[mid + k]. We should shift right if and only if arr[mid + k] is strictly closer to x than arr[mid].
The critical comparison is: x - arr[mid] > arr[mid + k] - x
Notice we use signed differences rather than absolute values. This handles all cases correctly:
- When both elements are on the same side of
x, it compares their distances properly - When they're on opposite sides, the element closer to
xnaturally wins - When distances are equal, the inequality is false, keeping the smaller value (left element)
The comparison is monotonic: as mid increases, x - arr[mid] decreases and arr[mid + k] - x increases (since the array is sorted). This guarantees binary search works correctly.
Why It Works
The signed comparison without absolute values is crucial for handling duplicate values. If we used |x - arr[mid]| > |arr[mid + k] - x|, when both elements equal the same value, both sides would be zero, and the search could move in the wrong direction. The signed version correctly evaluates such cases: if both arr[mid] and arr[mid + k] equal some value v, then x - v compared to v - x tells us which side of v the target lies on, guiding the search appropriately.
Complexity
Time Complexity: O(log(n - k) + k)
- Binary search over the valid starting positions: O(log(n - k))
- Slicing the result: O(k)
Space Complexity: O(1) auxiliary space (the output list of size k is required by the problem)
Solution Code
from typing import List
def closest_k_elements(arr: List[int], k: int, x: int) -> List[int]:
lo, hi = 0, len(arr) - k
while lo < hi:
mid = (lo + hi) // 2
if x - arr[mid] > arr[mid + k] - x:
lo = mid + 1
else:
hi = mid
return arr[lo:lo + k]