This practice workspace is built for desktop. Open it on a larger screen to start solving.
Find K Closest Elements
Given a sorted integer array arr, an integer k, and an integer x, return the k closest integers to x in the array. The result must be returned in ascending order.
An integer a is closer to x than b if |a - x| < |b - x|. When two elements are equidistant from x, the smaller integer is considered closer.
A heap solution is natural — push each element keyed by (|v - x|, v) and pull the k smallest — but a binary-search + two-pointer sliding window is more efficient. Either is acceptable; the result must be sorted ascending.
Examples
Constraints
- 1 <= k <= arr.length
- 1 <= arr.length <= 10^4
- arr is sorted in ascending order.
- -10^4 <= arr[i], x <= 10^4
Preview Mode
This is a read-only preview of DSAMind's AI coaching. Sign up to get custom feedback on your own solution.
Your approach
- Pattern:Heap
- Time:O(N)
- Space:O(1)
Complete approach — pattern and complexity both named.
Coach
What you got right
You correctly matched the sorted input requirement and implemented a linear-time scan using two pointers.
Where it diverged
No divergence detected. The code correctly aligns with the stated approach.
Next attempt: focus on
Try solving related sliding window problems to build familiarity with two-pointer variants.
Signals
No signals fired — clean run, you stayed in flow.