Input: arr[] = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56], k = 4, x = 35
Output: 39 30 42 45
Explanation: First closest element to 35 is 39.
Second closest element to 35 is 30.
Third closest element to 35 is 42.
And fourth closest element to 35 is 45.
Input: arr[] = [1, 3, 4, 10, 12], k = 2, x = 4
Output: 3 1
Explanation: 4
is excluded, Closest elements to 4
are: 3 (1)
, 1 (3)
. So, the 2 closest elements are: 3 1
The idea is to use the absolute difference between each element and the target value to measure how close they are. Then, we apply custom sorting: elements with smaller differences come first, and in case of a tie, the larger element is preferred. we take the k element from get from custrom sorted array then return it.
The idea is to first go through the array to find the last element that is less than or equal to the target value, skipping the target if it's present. Then, we use two pointers to choose the k closest elements by comparing their differences, while following the tie-breaking rules.