Community Problem

Find K Closest Elements

Difficulty: Medium

Find a length-k window in a sorted array whose elements are closest to x, using a binary search on the LEFT edge of the window.

Find K Closest Elements

Find a length-k window in a sorted array whose elements are closest to x, using a binary search on the LEFT edge of the window.

MEDIUM
Free
binary-search
two-pointers
arrays
jameszhang

By @jameszhang

January 20, 2026

·

Updated May 20, 2026

786 views

19

4.5 (14)

I see candidates default to the heap solution on this one and the interviewer always asks the follow-up: can you do it in O(log n + k) instead of O(n log k)? The trick is realizing the answer is a contiguous window and binary-searching for the WINDOW LEFT EDGE, not for the value of x. That reframing is the whole insight.

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 must be sorted in ascending order.

An integer a is closer to x than b if |a - x| < |b - x|. Ties break in favor of the smaller value: |a - x| == |b - x| and a < b makes a closer.

Examples

Example 1:

  • Input: arr = [1, 2, 3, 4, 5], k = 4, x = 3
  • Output: [1, 2, 3, 4]
  • Explanation: All five elements differ by at most 2 from 3, but the window [1, 2, 3, 4] has total absolute distance 4 vs [2, 3, 4, 5] total 4. Tie breaks toward smaller values, so the left window wins.

Example 2:

  • Input: arr = [1, 2, 3, 4, 5], k = 4, x = -1
  • Output: [1, 2, 3, 4]
  • Explanation: All elements are >= -1, so the closest k start at the left.

Example 3:

  • Input: arr = [1, 1, 1, 10, 10, 10], k = 1, x = 9
  • Output: [10]
  • Explanation: 10 is at distance 1 from 9; any 1 is at distance 8.

Example 4:

  • Input: arr = [0, 0, 1, 2, 3, 3, 4, 7, 7, 8], k = 3, x = 5
  • Output: [3, 3, 4]
  • Explanation: Closest three are 3, 3, 4. The 7 is at distance 2, but 4 is at distance 1, so 4 wins; second 3 is at distance 2, equal to 7, tie breaks to the smaller value.

Constraints

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 10^4
  • arr is sorted in ascending order.
  • -10^4 <= arr[i], x <= 10^4

Follow-up

The heap solution is O(n log k). Can you do it in O(log n + k)? Hint: the answer is a contiguous window of length k. Binary-search for the left edge of that window in the index range [0, arr.length - k].

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems