This problem follows the Max-Heap of Size K pattern, commonly found in the Heap / Priority Queue category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Use a max-heap of size k. If new point is closer than heap top, replace.
Use squared distances to avoid computing square roots — relative ordering is preserved. A max-heap of size k evicts the farthest point.
heap = []
for x, y in points:
dist = x*x + y*y
if len(heap) < k:
heappush(heap, (-dist, [x, y]))
elif -dist > heap[0][0]:
heapreplace(heap, (-dist, [x, y]))
return [p for _, p in heap]Practice K Closest Points to Origin and similar Heap / Priority Queue problems with flashcards. Build pattern recognition through active recall.
Practice this problem