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 problem
0
Problem

Find K Closest Elements

LeetCode #658Medium
Max-heap keyed by (distance, value)

Given 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.

Asked atAmazonGoogle
step 1 / 21
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, k
2rank each value by (|a − x|, a)
3take the best k
4return them sorted
state
  • x6
  • k3

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.