Find K Closest Elements
Master this topic with zero to advance depth.
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
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.
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].
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.
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.
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.
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).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.