FAANGPrep Sprint
Find K Closest Elements
Find k closest integers to a given value x.
Problem Understanding
From the sorted integer array arr, pick the k values nearest to x.
If |a - x| == |b - x|, the smaller number is chosen. The result should be sorted in ascending order.
Example:
- Input:
arr = [1,2,3,4,5],k = 4,x = 3 - Output:
[1,2,3,4]
Algorithm Strategy
The heap baseline — O(n log k). Treat it like any top-k problem: push every value onto a max-heap keyed by (|value − x|, value) and pop whenever it holds more than k. It works on any array, sorted or not.
A sorted array does better — O(n). Distance from x only falls and then rises along a sorted array, so the k closest values are one contiguous run, and the farther end of any window is its farthest value. Start with the whole array as the window [L, R] and shrink it:
- While the window holds more than k values, compare its two ends.
- If
arr[L]is strictly farther fromxthanarr[R], dropL. - Otherwise drop
R— on a tie the smaller value,arr[L], is the one to keep. - Return
arr[L..R].
Binary search can find where the window starts in O(log(n − k)); the shrink is the simplest correct version, and it is what the code below does.
Interactive Visualization
k = 3 · x = 5 · A TIE KEEPS THE SMALLER VALUE
WHOLE ARRAY
arr · |value − 5| beneath
L
4
3
2
1
0
1
R
2
Window
7
|arr[L] − x|
4
|arr[R] − x|
2
The window starts as the whole array: L = 0, R = 6
Next
7 values > k = 3. |1 - 5| = 4 against |7 - 5| = 2
arr
k
x
The window [L, R] starts as the whole array, with each value's distance from x beneath it. Its two ends are compared and the farther one is dropped until k values remain.
