SDE & MLE Prep

658. Find K Closest Elements

Problem

arr is sorted. Return the k values closest to x, sorted ascending. a is closer than b if |a − x| < |b − x|, or if the distances are equal and a < b.

Example: arr = [1,2,3,4,5], k = 4, x = 3 → [1,2,3,4]

Constraints: n ≤ 10⁴.

The answer is a window arr[i .. i+k). Binary search its start i ∈ [0, n−k]: if x − arr[mid] > arr[mid+k] − x, the window should move right.

Complexity: O(log(n − k) + k).

class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        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]