mediumHeapHeap / Priority Queue

K Closest Points to Origin

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

Signals to notice

find k closest points to originpartial sort / selectiondistance comparison

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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