Find K Closest Elements (LeetCode 658): Solution and Explanation

Medium
Array
Two Pointers
Binary Search
Sorting
Heap

Given a sorted array, a count k and a target x, return the k values closest to x, in ascending order. When two values are equally close, the smaller one wins.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A direct approach sorts the whole array by distance to x and takes the first k, then sorts those again by value. That is O(n log n) and ignores the fact that the array is already sorted.

The sorted order gives a stronger property: the answer is always a contiguous block of k elements. If some value were picked while a closer value between it and x was skipped, swapping them would improve the answer. So the real question is only where that window of length k starts, and the start can be anywhere from 0 to n - k.

Binary search on that start position. Suppose the window starts at mid, so it covers arr[mid] through arr[mid + k - 1]. Compare it with the window shifted one step right, which drops arr[mid] and adds arr[mid + k]. If x - arr[mid] is greater than arr[mid + k] - x, the left element is farther than the element just outside on the right, so the best window starts later and left = mid + 1. Otherwise the current start or something earlier is at least as good, so right = mid.

Notice the comparison uses signed differences rather than absolute values. That is deliberate: when both arr[mid] and arr[mid + k] are on the same side of x, the signed form still points the search in the right direction, and the strict greater than sign keeps ties on the left, matching the rule that smaller values win.

Approach: Binary search on the window start

  1. Set left = 0 and right = len(arr) - k, the range of possible starting indices.
  2. While left < right, compute mid = (left + right) // 2.
  3. If x - arr[mid] > arr[mid + k] - x, the window should move right, so set left = mid + 1.
  4. Otherwise set right = mid, keeping the current start as a candidate.
  5. When the bounds meet, return the slice arr[left:left + k], which is already sorted.

Step-by-step example

arr = [1,3,5,7,9,11], k = 2, x = 6
  1. The window can start anywhere from 0 to 4, so left = 0 and right = 4.
  2. mid = 2. Compare 6 - 5 = 1 with arr[4] - 6 = 3. 1 is not greater than 3, so right = 2.
  3. mid = 1. Compare 6 - 3 = 3 with arr[3] - 6 = 1. 3 is greater than 1, so left = 2.
  4. Now left == right == 2, so the loop stops.
  5. Return arr[2:4], which is [5,7]. Both values are 1 away from 6, which is the best any pair can do.

Code: Python, Java, C++

1class Solution:
2    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
3        left, right = 0, len(arr) - k
4
5        while left < right:
6            mid = (left + right) // 2
7            # Compare distance from x to left vs right of window
8            if x - arr[mid] > arr[mid + k] - x:
9                left = mid + 1
10            else:
11                right = mid
12
13        return arr[left:left + k]

Time and space complexity

Time

O(log(n - k) + k)

The binary search runs over n - k + 1 candidate starts, taking O(log(n - k)) steps, and building the final slice copies k elements.

Space

O(1)

Apart from the output slice, the search uses only a few integer variables.

Other approaches

Two pointers shrinking from both ends (time O(n - k), space O(1))

Start with the whole array and repeatedly drop whichever end is farther from x, preferring to drop the right end on ties, until k elements remain. It is easy to explain and needs no binary search reasoning.

Max heap by distance (time O(n log k), space O(k))

Push each element keyed by its distance to x (and value for ties) into a max heap capped at size k, then sort the survivors. It also works for unsorted input but wastes the sorted order here.

Common mistakes

  • Setting right = len(arr) - 1. The window must fit, so the last valid start is len(arr) - k, and a larger bound makes arr[mid + k] go out of range.
  • Comparing abs(x - arr[mid]) with abs(arr[mid + k] - x). When both values lie on the same side of x and are equal, absolute values can send the search the wrong way, for example with duplicate values.
  • Using >= instead of >. On a tie the smaller value should win, which means keeping the window to the left.
  • Returning the window without noting it is already sorted, then sorting it again, which is harmless but unnecessary.

Frequently asked questions

Why is the answer always a contiguous subarray?

The array is sorted, so values closer to x sit between x and values farther away. Any selection that skipped a closer value in favor of a farther one could be improved by swapping them, so the best k values form a single block.

Why compare arr[mid] with arr[mid + k]?

Those are the element that leaves and the element that enters when the window slides one step right. Whichever is closer to x tells you whether sliding right improves the window.

What is the time complexity of Find K Closest Elements?

The binary search is O(log(n - k)) and copying the result is O(k), for O(log(n - k) + k) overall. The two pointer version is O(n - k), and a heap is O(n log k).