Find K Closest Elements
Real-world version: Nearest Gauge MarksThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard 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)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Intersection of Two ArraysReal-world version: Shared Scan CodesEasy
- Earliest Finish Time for Land and Water Rides IReal-world version: Forge and Kiln BookingEasy
- Intersection of Two Arrays IIReal-world version: Shared Spare PartsEasy
- Check If N and Its Double ExistReal-world version: Twice Some Other EntryEasy