Heaps: K Closest Points

A heap keeps the smallest item at the front. heapq.heappush and heapq.heappop are O(log n), and heap[0] peeks at the smallest in O(1). Python's heap is a plain list managed by the heapq functions.

The signal: "top k", "k smallest", "k largest", or merging sorted streams.

For the k smallest of n items, heapq.nsmallest(k, items, key=...) runs in O(n log k), which beats sorting everything when k is small. To merge k sorted lists, heapq.merge keeps one item from each list in a heap.

Heaps compare tuples item by item, so push (priority, item). Python has only a min-heap: for a max-heap, push the negated priority.

A common mistake: computing a real distance with math.sqrt. Squared distances order the points the same way and stay exact integers.

Exercise: finish k_closest so it returns the k points closest to (0, 0), nearest first. Break ties by the point itself, so (-1, 0) comes before (0, 1). Press Check to run the tests.