Find K Closest Elements
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Binary Search.
Find K Closest Elements
Given a sorted integer array
arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.Examples
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
Approach 1
Level I: Brute Force (Sort by Distance)
Intuition
Calculate the absolute difference of each element from . Sort the array based on these distances. In case of a tie, the smaller element comes first. Return the first elements.
⏱ $O(N \\log N)$💾 $O(N)$
Detailed Dry Run
arr = [1,2,3,4,5], k = 4, x = 3
- Distances: [2, 1, 0, 1, 2]
- Sorted by (dist, val): [(0,3), (1,2), (1,4), (2,1), (2,5)]
- Take k=4: [3, 2, 4, 1]
- Sort Result: [1, 2, 3, 4].
Approach 2
Level II: Binary Search + Two Pointers
Intuition
Use binary search to find the position closest to . Then expand outwards using two pointers to find the closest elements.
⏱ $O(\\log N + K)$💾 $O(K)$
Detailed Dry Run
arr = [1,2,3,4,5], k=4, x=3
- BS for 3: index 2.
- L=1, R=3. Compare arr[1]=2 and arr[3]=4.
- Keep expanding until k=4 is reached.
Approach 3
Level III: Optimal (Binary Search on Window Start)
Intuition
We want a contiguous window of k elements from the sorted array. Binary search for the LEFT endpoint of that window. For a candidate window starting at
mid, compare if x - arr[mid] (distance to left edge) is greater than arr[mid+k] - x (distance to right edge). If left edge is farther, shift window right.⏱ O(log(N-K)) — binary search on start index.💾 O(1) extra — the result itself is O(K).
Detailed Dry Run
Input:
arr=[1,2,3,4,5], k=4, x=3
| Step | l | r | mid | arr[mid] | arr[mid+k] | dist left | dist right | Decision |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| 1 | 0 | 1 | 0 | 1 | 5 | 3-1=2 | 5-3=2 | Equal, go left: r=0 |
| l==r==0 → window=[arr[0]..arr[3]]=[1,2,3,4]** |⚠️ Common Pitfalls & Tips
The search bounds are
[0, N-K] (not [0, N-1]). The tie-breaking rule is: when x - arr[mid] == arr[mid+k] - x, prefer the smaller element (i.e., r = mid, not l = mid+1).Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.