KatInterview

Find K Closest Elements in Sorted Array

Heaps, Sorting & SearchAuto-graded · 26 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchtwo-pointerssliding-window

Last 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| and a < 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 x does 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^4
  • arr is 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.