mediumBinary SearchPure DSA~25 min
K Readings Closest to a Target
From a sorted list of calibration readings, return the k readings nearest a target value, in ascending order — for displaying the most relevant neighbors around a setpoint.
Problem
Given a sorted integer array arr, an integer k, and an integer x, return the k closest values to x, sorted ascending. Closeness ties favor the smaller value: |a - x| < |b - x|, or |a - x| == |b - x| and a < b.
Input
A sorted array arr, an integer k, and an integer x.
Output
An array of the k closest values in ascending order.
Constraints
- 1 <= k <= arr.length <= 10^4
- arr is sorted ascending; -10^9 <= arr[i], x <= 10^9.
Examples
Example 1
Input
arr = [1,2,3,4,5], k = 4, x = 3
Output
[1,2,3,4]
The four closest to 3, ties favoring smaller, are 1..4.
Example 2
Input
arr = [1,1,2,3,4,5], k = 4, x = -1
Output
[1,1,2,3]
All small values are nearest to -1.