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 INPUT Sorted Array arr: 1 2 3 4 5 0 1 2 3 4 Parameters: k = 4 x = 3 (target) n = 5 (array length) Distance from x=3: |2| |1| |0| |1| |2| ALGORITHM STEPS 1 Binary Search Find left bound for window left=0, right=n-k=1 2 Compare Distances x-arr[mid] vs arr[mid+k]-x Shrink search space 3 Narrow Window Move left or right ptr Until left == right 4 Extract Result Return arr[left:left+k] Binary Search Process: Iter 1: mid=0 3-1=2 vs 5-3=2 Equal: prefer left right=0 Result: left=0 FINAL RESULT K Closest Elements to x=3: 1 2 3 4 Output: [1, 2, 3, 4] Verification: - Returned k=4 elements - Sorted in ascending order - Closest to x=3: OK Complexity: Time: O(log(n-k) + k) Space: O(1) Key Insight: Binary search finds the optimal starting index for a window of size k. Instead of checking all elements, we compare distances at window boundaries: if x is closer to arr[mid+k], move right; otherwise stay left. This reduces time complexity from O(n) to O(log(n-k)) for finding the window start position. TutorialsPoint - Find K Closest Elements | Optimal Binary Search 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