Given a sorted integer array, find the k closest elements to x in the array where k and x are given positive integers.
The integer x may or may not be present in the input array. If x is less than or equal to the first element in the input array, return first k elements. Similarly, if x is more than or equal to the last element in the input array, return the last k elements. The returned elements should be in the same order as present in the input array.



For example,

The idea is to do a linear search to find the insertion point i. The insertion point is defined as the point at which the key x would be inserted into the array, i.e., the index of the first element greater than the key, or the array’s size if all elements in the array are less than the specified key. Then, compare the elements around the insertion point i to get the first k closest elements. The time complexity of this solution is O(n).
We can also find the insertion point i using binary search algorithm which runs in O(log(n)) time. Since finding the k closest elements takes O(k) time, the overall time complexity of this solution is O(log(n) + k). Below is the implementation in C, C++, Java and Python based on the this idea.

C

Download   Run Code

Output:

12 15 17 18

C++

Download   Run Code

Output:

12 15 17 18

Java

Download   Run Code

Output:

[12, 15, 17, 18]

Python

Download   Run Code

Output:

[12, 15, 17, 18]

Download   Run Code
Output:

12 15 17 18

Download   Run Code
Output:

12 15 17 18

Download   Run Code
Output:

[12, 15, 17, 18]

Download   Run Code
Output:

[12, 15, 17, 18]

The above solution to do a binary search to find the insertion point and then tries to find the k closest elements. However, we can combine the whole logic in a single binary search routine. Here’s how the algorithm would look like in C, Java, and Python.

C

Download   Run Code

Output:

12 15 17 18

Java

Download   Run Code

Output:

[12, 15, 17, 18]

Python

Download   Run Code

Output:

[12, 15, 17, 18]

Download   Run Code
Output:

12 15 17 18

Download   Run Code
Output:

[12, 15, 17, 18]

Download   Run Code
Output:

[12, 15, 17, 18]

The time complexity of above solution is O(n) and auxiliary space used by the program is O(1).

source