You are given a sorted integer array arr[], an integer k, and an integer x. Your task is to find the k closest elements to x in the array. An element a is closer to x than element b if the absolute difference |a - x| is smaller than |b - x|. If there is a tie, choose the smaller element. Return the k closest elements in ascending order.
Example 1
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Explanation: The elements closest to 3 are 3, 2, 4, and 1. After sorting them in ascending order, the result is [1,2,3,4].
Example 2
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
Explanation: Since x = -1 is smaller than all elements, the first 4 elements are the closest.
Example 3
Input: arr = [2,4,5,6,9], k = 3, x = 7
Output: [5,6,9]
Explanation: The elements closest to 7 are 6, 5, and 9. After sorting them in ascending order, the result is [5,6,9].
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 2 3 4 5 4 3
1 2 3 4
1 2 3 4 5 4 -1
1 2 3 4