Find k Nearest Values in Sorted Array
Heaps, Sorting & SearchAuto-graded · 26 test casesLast updated
Tests binary search on window positions with careful tie-breaking that prefers smaller values when distances are equal.
You are given an integer array nums sorted in ascending order, an integer count, and a target integer target. Your task is to find the count values in nums that have the smallest absolute distance to target. Return them in ascending order.
When two values have equal distance to target, the smaller value is considered closer.
Each position in the array counts as a separate element. If a value appears multiple times, it can be selected multiple times.
Rules
- Value
ais closer totargetthan valuebif:|a - target| < |b - target|, OR|a - target| == |b - target|anda < b
- The target value does not need to exist in
nums - The target may be smaller than all values or larger than all values in the array
- Your output must be sorted in ascending order
Constraints
1 <= count <= len(nums) <= 10^4numsis sorted in non-decreasing order-10^4 <= nums[i], target <= 10^4
Examples
Example 1
Input: find_nearest_values([1, 3, 5, 8, 12], 3, 6)
Output: [3, 5, 8]
Example 2
Input: find_nearest_values([2, 4, 6, 8], 3, 5)
Output: [2, 4, 6]
Example 3
Input: find_nearest_values([1, 1, 2, 2, 2, 5], 4, 2)
Output: [1, 2, 2, 2]
Hints
Hint 1
The answer always forms a contiguous subarray of length count. Why can't the closest values be scattered?
Hint 2
Use binary search to find the optimal starting position for a window of size count, not to search for the target value itself.
Hint 3
Compare windows by their endpoints: if window starting at i contains nums[i] and window starting at i+1 contains nums[i+count] instead, which endpoint is closer to target?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that the count closest values always form a contiguous subarray in the sorted input. This is because distance to the target decreases monotonically as you move toward the target from either direction. If we skipped an element between two chosen ones, that middle element would be closer than at least one of the chosen elements, creating a contradiction.
Therefore, the problem reduces to finding the optimal starting index for a window of size count.
We use binary search on the range of valid starting positions [0, n - count]. To decide whether to search left or right, we compare adjacent windows. Window starting at position i contains nums[i], while window starting at i + 1 replaces nums[i] with nums[i + count]. We compare these two endpoints:
- If
target - nums[i] > nums[i + count] - target, thennums[i + count]is strictly closer, so we shift the window right - Otherwise,
nums[i]is at least as close. When distances are equal,nums[i]is the smaller value and wins by the tie-breaking rule, so we keep searching left
The comparison works without absolute values because:
- When both endpoints are on the same side of target, the differences have consistent signs and the closer value is correctly identified
- When the window straddles target, both differences are true distances
- Ties are resolved by the
>(not>=) operator, which correctly prefers the smaller value on the left
Why It Works
The predicate target - nums[i] > nums[i + count] - target can be rewritten as nums[i] + nums[i + count] < 2 * target. Since the array is sorted, nums[i] + nums[i + count] increases monotonically with i. This means the predicate is true for a prefix of positions and false thereafter, making binary search applicable.
Complexity
- Time: O(log(n - count) + count). Binary search over at most
n - count + 1positions takes O(log(n - count)), and slicing the result takes O(count). - Space: O(count) for the output array, O(1) auxiliary space.
This is more efficient than sorting by distance (O(n log n)) or using a heap (O(n log count)).
Solution
from typing import List
def find_nearest_values(nums: List[int], count: int, target: int) -> List[int]:
n = len(nums)
left, right = 0, n - count
while left < right:
mid = (left + right) // 2
# Compare the endpoints of adjacent windows
# Window at mid includes nums[mid], window at mid+1 includes nums[mid+count]
if target - nums[mid] > nums[mid + count] - target:
left = mid + 1
else:
right = mid
return nums[left:left + count]