mediumHeapHeap / Priority Queue

K Closest Points to Origin

mediumTime: O(n log k)Space: O(k)

Recognize the pattern

find k closest points to originpartial sort / selectiondistance comparison

Brute force idea

A straightforward first read of K Closest Points to Origin is this: Compute all distances, sort, take first k. Full sort is unnecessary for partial selection. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The deeper shift in K Closest Points to Origin is this: Max-heap of size k: for each point, compute distance and add to heap. If heap size > k, remove the farthest (heap max). After all points, the heap contains the k closest. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of K Closest Points to Origin is one steady idea: The max-heap's top is always the farthest of the current k closest. Any point closer than the top displaces it — ensuring the heap always holds the k closest seen so far. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in K Closest Points to Origin usually looks like this: Using Euclidean distance with square root — you don't need sqrt for comparison. x² + y² is sufficient and avoids floating-point precision issues. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Heap / Priority Queue Pattern