K Closest Points to Origin
MediumNeetCode 150 Heap / Priority QueueAsanaWixMetaProblem
You are given a list of points on a plane, each written as [x, y], and an integer
k. Return the k points that are closest to the origin (0, 0), using
ordinary straight-line distance.
The points may be returned in any order. The tests only use inputs where the answer set is unique.
Constraints
- 1 ≤ k ≤ points.length ≤ 10⁴
- −10⁴ ≤ x, y ≤ 10⁴
Examples: pick one to animate
Solutions
Time: Each of the n points does one push and at most one pop on a heap of at most k + 1 entries, and sifting walks at most log k levels.
Space: The distance array holds one number per point. The heap itself never keeps more than k + 1 indices.
Keep only the k closest points seen so far in a max-heap ordered by squared distance. The root is the farthest of the kept points, which makes it the right one to throw out: after each push, if the heap holds more than k points, pop the root. Squared distance ranks points exactly like real distance, so no square root is needed. The code uses its own array heap of point indices (parent of index i is (i − 1) / 2), so the array and tree you see are the real thing.