1
3
5
7
9
11
[0][1][2][3][4][5]
distance to x = 6
·
·
·
·
·
·
[0][1][2][3][4][5]
Brute force · sort by distance
▸1given arr, x, k2rank each value by (|a − x|, a)3take the best k4return them sorted
state
- x6
- k3
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problemGiven a sorted array, a value k, and a target x, return the k elements closest to x as a sorted list. When two elements are equally close, prefer the smaller one.
▸1given arr, x, k2rank each value by (|a − x|, a)3take the best k4return them sorted
line 1From a SORTED array, return the k = 3 values closest to x = 6. Closeness = |a − 6|; ties go to the SMALLER value. Simple plan: rank every element by distance.