Given an array of points where points[i] = [xi, yi] and the origin [0, 0], return the k closest points to the origin. Distance is Euclidean. You may return the answer in any order.
points = [[1,3],[-2,2]], k = 1[[-2,2]]points = [[3,3],[5,-1],[-2,4]], k = 2[[3,3],[-2,4]]size > k: evict max (farthest) — root of max-heapCounter-intuitive but elegant: to keep the k smallest distances, use a MAX-heap. The root is always the farthest point in your current selection. When a new point arrives and the heap is full (k+1 items), you evict the root — the current farthest. What remains is always the k closest seen so far. Using dist² instead of dist avoids the sqrt operation while preserving comparison order.
Sorting all points by distance takes O(n log n). We only need the k closest ones.
Compare squared distances, x squared plus y squared, so no square root is needed. Keep a max heap of at most k points, ordered by distance. The root is the farthest point among the current k closest. When a new point makes the heap bigger than k, poll the root, because it is the worst candidate.
For the k smallest, use a max heap of size k. Compare squared distances to skip the square root.
Run the animation above on your own input, or watch the 1:43 video explanation of K Closest Points to Origin with a dry run and Java code.