Code RoomClosest k elements to x
MediumPrep Room Coding #1231

Closest k elements to x

CodingAlgorithms & data structuresMid–Senior~22 min

Given a sorted ascending integer array `arr`, an integer `k`, and an integer `x`, return the `k` elements closest to `x`, in ascending order. Closeness ties break toward the smaller value (|a-x| < |b-x|, or equal and a < b). 1 <= k <= len(arr). Aim for O(log n + k): binary-search for the best left boundary of the size-k window rather than sorting by distance.

Implement
find_closest_elements(arr: list[int], k: int, x: int) → list[int]
Examples
in[[1,2,3,4,5],4,3]out[1,2,3,4]
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 22 min
InputExpectedGot
[[1,2,3,4,5],4,3][1,2,3,4]not run yetsample