Locate K Nearest Values in a Sorted Sequence
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Binary search for the starting boundary of a contiguous k-element slice minimizing distance to a given target in a sorted list.
Given an array of integers arr sorted in non-decreasing order, a non-negative integer k, and a target value target, locate the k values in arr that lie closest to target.
Distance between an element x and target is measured by the absolute difference |x - target|.
If two elements are equally close to target, the smaller element takes precedence.
The final result must be returned as a contiguous subarray formatted in sorted ascending order.
Constraints
1 <= k <= len(arr)1 <= len(arr) <= 10^4arris sorted in non-decreasing order.- Integers in
arrandtargetfall within[-10^4, 10^4].
Examples
Example 1
Input: find_k_closest_values([1, 2, 3, 4, 5], 4, 3)
Output: [1, 2, 3, 4]
Example 2
Input: find_k_closest_values([1, 10, 15, 25], 2, 20)
Output: [15, 25]
Hints
Hint 1
Notice that the optimal k elements must form a single contiguous window of length k in the sorted array.
Hint 2
Instead of selecting elements one by one, can you search for the starting index of this length-k window?
Hint 3
Compare the element leaving the window at index `mid` with the element entering at index `mid + k`. Use signed distance rather than absolute values to avoid edge-case failures with duplicates.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
Since arr is already sorted, any set of $k$ closest elements must form a contiguous block (a window) of length $k$. Therefore, the problem reduces to finding the optimal starting index $i$ of this window, where $0 \le i \le n - k$.
We can binary search for the correct starting index $i$:
- At any candidate start index
mid, consider the windowarr[mid : mid + k]. - Compare the element at the left boundary of the window (
arr[mid]) with the element just outside the right boundary (arr[mid + k]). - If shifting the window to the right improves (or maintains) proximity to
target, thenarr[mid]is farther fromtargetthanarr[mid + k]. This condition holds when: $$\text{target} - \text{arr}[\text{mid}] > \text{arr}[\text{mid} + k] - \text{target}$$ - If this inequality is true, the optimal start index must be to the right of
mid(setleft = mid + 1). Otherwise, the optimal start index is atmidor to its left (setright = mid).
Using signed distances (target - arr[mid]) instead of absolute values (abs(...)) ensures that ties are resolved properly and that duplicate values in arr are handled correctly without infinite loops or wrong index selections.
Complexity Analysis
- Time Complexity: $O(\log(n - k) + k)$. The binary search executes in $O(\log(n - k))$ steps, and retrieving the slice of length $k$ takes $O(k)$ time.
- Space Complexity: $O(1)$ auxiliary space beyond the output array of size $O(k)$.
Python Source Code
from typing import List
def find_k_closest_values(arr: List[int], k: int, target: int) -> List[int]:
left, right = 0, len(arr) - k
while left < right:
mid = (left + right) // 2
if target - arr[mid] > arr[mid + k] - target:
left = mid + 1
else:
right = mid
return arr[left:left + k]