15/40
Part 4 of 8 · The k bestLearn and do

For the k smallest, negate, so the largest kept item is on top

The k smallest run the other way. The window sits at the low end, and its weakest member is the largest value kept. That's the one a newcomer replaces, so it has to be on top. That's a max-heap, built by negating:

def k_smallest(values, k):
    # negated: the largest kept value on top
    heap = []
    for x in values:
        if len(heap) < k:
            heapq.heappush(heap, -x)
        # x is smaller than the largest kept
        elif -x > heap[0]:
            heapq.heapreplace(heap, -x)
    return sorted(-x for x in heap)


print(k_smallest([5, 1, 8, 3, 9, 2, 7, 4], 3))
[1, 2, 3]

heapq.nsmallest and heapq.nlargest do this for you, and most items cost them one comparison.

The squared distance orders points the same way the distance does, and it skips a square root per point.

In the editor, KClosest keeps the k points closest to the origin while points arrive one at a time, and closest() reads them out. Write add(point), with the farthest kept point on top of self.heap.