Heap
Keep only k winners
Why it matters
Nearest-store results, anomaly dashboards, and recommendation feeds often need a small top-k answer from millions of records or an endless stream. Sorting and retaining every record delays the first answer and uses memory unrelated to k. The process must retain only the k closest candidates while reading each point once.
Example
K Closest Points to Origin
Return the k points closest to (0,0) (Euclidean). Order does not matter; tests sort by (x, y) after you return.
- Input
- points = [[3, 3], [5, -1], [-2, 4]], k = 2
- Output
- [[-2, 4], [3, 3]]
Approach 2 · Resolve the bottleneck
The idea
Keep one example in view
K Closest Points to Origin
points = [[3, 3], [5, -1], [-2, 4]], k = 2→[[-2, 4], [3, 3]]
The baseline, Sort every point, is O(n log n) · O(n). The better model below keeps this exact input and removes that bottleneck.
For [[3, 3], [5, −1], [−2, 4]] with k = 2, brute sorting ranks all three points. Keep only two entries, with distance 26 on top; when distance 20 arrives, evict 26 and retain distances 18 and 20.
For [3, 3], [5, −1], and [−2, 4], squared distances are 18, 26, and 20. Store negative distances so the farthest retained point has the smallest key. After the first two pushes, [5, −1] with key −26 is at the root.
Push [−2, 4] with key −20, making three entries while k = 2. Pop −26, which evicts [5, −1]. The heap now holds [3, 3] and [−2, 4]; their internal order does not matter because either output order is accepted.
Visual anchor
K Closest Points to Origin
Pro
The rest of this is on Pro
The idea above is free. The walkthrough, the cost, and the practice are on Pro.