
'K' Closest Numbers (medium)
Problem Statement
Given a sorted number array and two integers K and X, find K closest numbers to X in the array. Return the numbers in the sorted order. X is not necessarily present in the array.
Example 1:
Input: [5, 6, 7, 8, 9], K = 3, X = 7
Output: [6, 7, 8]
Example 2:
Input: [2, 4, 5, 6, 9], K = 3, X = 6
Output: [4, 5, 6]
Example 3:
Input: [2, 4, 5, 6, 9], K = 3, X = 10
Output: [5, 6, 9]
Constraints:
1 <= k <= arr.length- 1 <= arr.length <= 10<sup>4</sup>
- arr is sorted in ascending order.
- -10<sup>4</sup> <= arr[i], x <= 10<sup>4</sup>
- If two numbers are equally far from
x, prefer the smaller one. In[1, 3, 5, 7, 9]with K = 1 and X = 6, both 5 and 7 are one away, and the answer is 5.
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory