KatInterview

Locate K Nearest Values in a Sorted Sequence

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchtwo-pointersarrays

Last 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^4
  • arr is sorted in non-decreasing order.
  • Integers in arr and target fall 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.