480. Find K Closest Elements in Sorted Array

MediumBinary SearchBinary SearchTwo PointersArray

Given a sorted array, an integer k, and a value x, return the k closest elements to x as a sorted array. Closeness is by absolute difference; ties prefer the smaller value. Input: '[arr], k, x'.

Input: '[arr], k, x'.

Output: Array — the k closest values, sorted ascending.

Examples

Example 1
Input: [1,2,3,4,5], 4, 3
Output: [1,2,3,4]
Explanation: Four closest to 3.
Example 2
Input: [1,2,3,4,5], 4, -1
Output: [1,2,3,4]
Explanation: x below range.
Example 3
Input: [1], 1, 1
Output: [1]
Explanation: Single element.

Constraints

Asked by

CapgeminiMetaAppleAmazonFlipkartGoogle
Solve this problem in the editor →