Given a sorted integer array, find the k closest elements to target in the array where k and target are given positive integers.

The target may or may not be present in the input array. If target is less than or equal to the first element in the input array, return first k elements. Similarly, if target 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,

Input:  [10, 12, 15, 17, 18, 20, 25], k = 4, target = 16
Output: [12, 15, 17, 18]
 
Input:  [2, 3, 4, 5, 6, 7], k = 3, target = 1
Output: [2, 3, 4]
 
Input:  [2, 3, 4, 5, 6, 7], k = 2, target = 8
Output: [6, 7]

Practice this problem

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 target 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), where n is the size of the input.

We can also find the insertion point i using the 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). Following is the implementation in C, C++, Java, and Python, based on 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]

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]

The time complexity of the above solution is O(n) and doesn’t require any extra space.