Trains the technique from
LeetCode 658Find K Closest ElementsThis 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.
Example 1
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
Both 3 and 5 sit one away from 4. The tie goes to the smaller reading, so 3 is returned.
Example 3
The distances are 7, 1, 2 and 6, so -3, 0 and 4 are the three nearest and -9 is left out.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def find_closest_elements(arr: list[int], k: int, x: int) -> list[int]:public List<Integer> findClosestElements(int[] arr, int k, int x)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.