Pattern visualizer
K Closest Points to Origin
The insight: you don't need to sort all n points by distance — you only need to know whether each new point beats the WORST of the k you're currently keeping. A max-heap of size k does exactly that: its root is always the farthest of your current k candidates, so a new point only needs one comparison against the root to know if it deserves a spot. Capping the heap at size k — evicting the farthest whenever a closer point arrives — gives O(n log k), cheaper than the O(n log n) a full sort would cost. Animated on: Find the k closest points to origin from a set of n points.
Max-heap of size k
Add (1,3) with dist=10 (1²+3²). Heap: [10]. Size 1 ≤ k=2. Keep current element.
1FUNCTION kClosest(points, k):2 heap = a max-heap keyed by distance3 FOR each point p in points:4 dist = p[0]*p[0] + p[1]*p[1]5 push p onto the heap with its dist6 IF heap size > k: pop the farthest (the max)7 END FOR8 RETURN the heap9END FUNCTION
← / → step · space play · Home restart