sagelearnai

Find K Closest Elements

Difficulty: Medium · Pattern: Binary Search · LeetCode #658

Given sorted arr, return the k elements closest to x, sorted ascending. a is closer than b if |a − x| < |b − x|, or if they're equally close and a < b.

Examples

text
arr = [1, 2, 3, 4, 5], k = 4, x = 3   →  [1, 2, 3, 4]
arr = [1, 1, 2, 3, 4, 5], k = 4, x = −1 →  [1, 1, 2, 3]

Hints

  1. The answer is a contiguous window of length k.
  2. Binary search its left edge L in [0, n − k]: compare x − arr[L] with arr[L + k] − x.

Approach

Search lo ∈ [0, n−k]. For mid, if x − arr[mid] > arr[mid + k] − x, the window should move right (lo = mid + 1); otherwise hi = mid. Ties favor the left (smaller values). Return arr[lo : lo + k]. O(log(n − k) + k).

Complexity

Time: O(log(n − k) + k). Space: O(1) extra.

Python solution
def findClosestElements(arr, k, x):
    lo, hi = 0, len(arr) - k
    while lo < hi:
        mid = (lo + hi) // 2
        if x - arr[mid] > arr[mid + k] - x:
            lo = mid + 1
        else:
            hi = mid
    return arr[lo:lo + k]
JavaScript solution
function findClosestElements(arr, k, x) {
  let lo = 0, hi = arr.length - k;
  while (lo < hi) { const mid = (lo + hi) >> 1; if (x - arr[mid] > arr[mid + k] - x) lo = mid + 1; else hi = mid; }
  return arr.slice(lo, lo + k);
}