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.

An integer a is closer to x than an integer b if:

  • |a - x| < |b - x|, or
  • |a - x| == |b - x| and a < b

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
💡 Note: The 4 closest elements to 3 are [1,2,3,4]. Distances: |1-3|=2, |2-3|=1, |3-3|=0, |4-3|=1, |5-3|=2. Elements 2,3,4 have distances 1,0,1 respectively, and 1 has distance 2, so we take [1,2,3,4].
Example 2 — Target Not in Array
$ Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
💡 Note: The 4 closest elements to -1 are the first 4 elements. Distances: |1-(-1)|=2, |2-(-1)|=3, |3-(-1)|=4, |4-(-1)|=5, |5-(-1)|=6. The smallest 4 distances correspond to elements [1,2,3,4].
Example 3 — Tie Breaking
$ Input: arr = [1,1,1,10,10,10], k = 1, x = 9
Output: [10]
💡 Note: Both 1 and 10 have distance |1-9|=8 and |10-9|=1 respectively to x=9. Since |10-9|=1 < |1-9|=8, we choose 10.

Constraints

  • 1 ≤ k ≤ arr.length
  • 1 ≤ arr.length ≤ 104
  • -104 ≤ arr[i], x ≤ 104
  • arr is sorted in ascending order

Visualization

Tap to expand
Find K Closest Elements ProblemInput: arr = [1,2,3,4,5], k = 4, x = 312345target x=3Calculate distances:|1-3|=2|2-3|=1|3-3|=0|4-3|=1|5-3|=2k=4 closest elements:1234Output: [1,2,3,4]
Understanding the Visualization
1
Input
Sorted array [1,2,3,4,5], k=4, x=3
2
Process
Find elements with minimum distance to x=3
3
Output
Return [1,2,3,4] in sorted order
Key Takeaway
🎯 Key Insight: Use binary search to find target position, then expand with two pointers for optimal O(log n + k) solution
Asked in
Amazon 45 Google 35 Facebook 28 Microsoft 22
125.0K Views
High Frequency
~25 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen