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 considered closer to x than integer b if:
โ€ข |a - x| < |b - x| (smaller absolute difference), or
โ€ข |a - x| == |b - x| and a < b (same distance but smaller value)

Example: For array [1,2,3,4,5], k=4, and x=3, the answer is [1,2,3,4] because these are the 4 numbers closest to 3.

Input & Output

example_1.py โ€” 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, and 4. Distance from 3: |1-3|=2, |2-3|=1, |3-3|=0, |4-3|=1, |5-3|=2. Taking the 4 smallest distances gives us [1,2,3,4].
example_2.py โ€” Tie-breaking case
$ Input: arr = [1,2,3,4,5], k = 4, x = -1
โ€บ Output: [1,2,3,4]
๐Ÿ’ก Note: When x=-1, all elements are on the right side. Distances: |1-(-1)|=2, |2-(-1)|=3, |3-(-1)|=4, |4-(-1)|=5, |5-(-1)|=6. The 4 closest are still [1,2,3,4].
example_3.py โ€” Single element
$ Input: arr = [1,2,3,4,5], k = 1, x = 3
โ€บ Output: [3]
๐Ÿ’ก Note: When k=1, we only need the single closest element to x=3, which is 3 itself with distance 0.

Visualization

Tap to expand
Finding K Closest Elements: Number Line AnalogyFriend1|1-3|=2Friend2|2-3|=1YOU3|3-3|=0Friend4|4-3|=1Far Friend5|5-3|=2Your 4 closest friendsKey insight: In a sorted array, your k closest elements will always be consecutive!This allows us to use efficient algorithms like binary search instead of sorting all distances.
Understanding the Visualization
1
Position Yourself
You stand at x=3 on the number line
2
Measure Distances
Calculate how far each friend is from your position
3
Find Optimal Window
Since friends are in a line, your k closest friends will be consecutive
4
Select the Group
Choose the contiguous group of k friends with minimal total distance
Key Takeaway
๐ŸŽฏ Key Insight: Since the array is sorted, the k closest elements always form a contiguous subarray, enabling O(log n) binary search instead of O(n log n) sorting!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array with two pointers, O(n-k) iterations maximum

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses constant extra space for pointers

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค k โ‰ค arr.length
  • 1 โ‰ค arr.length โ‰ค 104
  • arr is sorted in ascending order
  • -104 โ‰ค arr[i], x โ‰ค 104
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
42.3K Views
High Frequency
~18 min Avg. Time
1.8K 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