DIY: Find K Closest Elements
Solve the interview question "Find K Closest Elements" in this lesson.
We'll cover the following
Problem statement
Given a sorted integer array arr
, and two integers k
and x
, return the k
closest integers to x
in this array. You must ensure that the result is sorted in ascending order.
An ID a
is closer to num
than an ID b
, if |a - num| <= |b - num|
and a < b
.
Input
The input will be an array of integers and two integers. The following are examples of input to the function:
// Sample Input 1
arr = [1, 2, 3, 4, 5], k = 4, x = 3
// Sample Input 2
arr = [1, 2, 3, 4, 5], k = 4, x = -1
// Sample Input 3
arr = [-29, -11, -3, 0, 5, 10, 50, 63, 198], k = 6, x = 8
Output
The output will be a list of integers containing k
closest integers to x
. The following are examples of the outputs:
// Sample Output 1
[1, 2, 3, 4]
// Sample Output 2
[1, 2, 3, 4]
// Sample Output 3
[-29, -11, -3, 0, 5, 10]
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.