Basic example
Input
arr = [1, 2, 3, 4, 5], k = 4, x = 3
Output
[1, 2, 3, 4]
The four numbers closest to 3 are 1,2,3,4. They are returned in ascending order.
Full lesson preview
Given a sorted array, return the k elements closest to a target x in ascending order. Use two pointers for an optimal linear solution.
Problem statement
Task
Examples
Input
arr = [1, 2, 3, 4, 5], k = 4, x = 3
Output
[1, 2, 3, 4]
The four numbers closest to 3 are 1,2,3,4. They are returned in ascending order.
Input format
Output format
Constraints
Samples
Input
arr = [1, 2, 3, 4, 5], k = 4, x = -1
Output
[1, 2, 3, 4]
x is less than all elements, so return the first k elements.