Given an array of points on the plane and an integer k, return the k points closest to the origin (Euclidean distance), in any order.
Keep the k closest points seen so far in a max-heap keyed by distance. A new point that is closer than the heap's farthest replaces it.
1function kClosest(points: number[][], k: number): number[][] {2const dist = (p: number[]) => p[0] ** 2 + p[1] ** 2;3const heap = new MaxPriorityQueue<number[]>(dist);4for (const p of points) {5heap.enqueue(p);6if (heap.size() > k) heap.dequeue();7}8return heap.toArray();9}
Empty max-heap.
Space: play/pause · ←/→: step