All problems
0349MediumArrayTwo PointersBinary SearchSliding WindowSortingHeap (Priority Queue)

Nearest Gauge Marks

Tracked in this browser only
Write code

Trains the technique from

LeetCode 658Find K Closest Elements

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A calibration bench carries gauge marks etched along a rail. Their readings are listed in arr from lowest to highest, and the same reading may be etched more than once. A technician aims the probe at reading x and wants the k marks nearest to that aim.

Mark a is nearer than mark b when |a - x| is smaller than |b - x|, and when the two distances are equal the smaller reading is treated as the nearer one.

Return the k chosen readings listed from lowest to highest. When a reading is etched several times, each etching counts as its own mark.

Examples

Example 1

Input
arr = [2,5,9,13,20], k = 3, x = 10
Output
[5,9,13]

The distances from 10 are 8, 5, 1, 3 and 10. The three smallest belong to 9, 13 and 5, and the answer lists those readings from lowest to highest.

Example 2

Input
arr = [1,3,5,7], k = 1, x = 4
Output
[3]

Both 3 and 5 sit one away from 4. The tie goes to the smaller reading, so 3 is returned.

Example 3

Input
arr = [-9,-3,0,4], k = 3, x = -2
Output
[-3,0,4]

The distances are 7, 1, 2 and 6, so -3, 0 and 4 are the three nearest and -9 is left out.

Constraints

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 10^4
  • arr is listed from lowest to highest.
  • -10^4 <= arr[i] <= 10^4
  • -10^4 <= x <= 10^4

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def find_closest_elements(arr: list[int], k: int, x: int) -> list[int]:
Java
public List<Integer> findClosestElements(int[] arr, int k, int x)
September 7
Apply