KatInterview

Find k Nearest Values in Sorted Array

Heaps, Sorting & SearchAuto-graded · 26 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchsliding-windowtwo-pointers

Last 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 a is closer to target than value b if:
    • |a - target| < |b - target|, OR
    • |a - target| == |b - target| and a < 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^4
  • nums is 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?