Find the k points nearest the origin. Keep a max-heap of k seats and bump whoever sits farthest, so the k closest are left at the end.
▼The problem
LeetCode 973 (Medium). Given an array of points [x, y] on the plane and an integer k, return the k points closest to the origin (0, 0), in any order (the answer is unique up to order).
Examples (LeetCode's): [[1,3],[-2,2]], k = 1 → [[-2,2]] (scores 10 and 8; scene 2); [[3,3],[5,-1],[-2,4]], k = 2 → [[3,3],[-2,4]] (checked at load, not shown).
The solution
import heapq
def kClosest(points, k):
heap = [] # scores negated
for x, y in points:
heapq.heappush(heap, (-(x*x + y*y), x, y))
if len(heap) > k:
heapq.heappop(heap) # bump the farthest
return [[x, y] for _, x, y in heap]Transcript
K Closest Points to Origin. You get a list of points on a grid and a number k. Return the k points closest to the origin, zero zero, in any order.
How far is a point? Walk x across and y up, and the distance is the square root of x squared plus y squared. A square root never changes which is bigger, so skip it and compare x squared plus y squared. One three scores ten, minus two two scores eight, so with k equals one, minus two two wins.
The simple way scores every point, sorts them all, and keeps the first k. That's n log n time, and most of the sorting orders points you throw away. A million points with k equals three sorts nearly a million for nothing.
Better: make the origin a campfire with a bench of just k seats. Each newcomer sits down. If more than k are seated, whoever sits farthest from the fire is bumped. To find them fast, the bench is a max-heap, so the farthest always sits on top. Whoever is left is the k closest.
Python's heap keeps the smallest on top, so push each point with its score negated, and the farthest rises to the top. When the heap holds more than k, pop. Then return what remains.
Six points, k equals three. Twenty, ten and thirty-four fill the bench, and thirty-four sits on top. Five arrives, four are seated, so thirty-four is bumped. Seventeen arrives, and twenty is bumped. Twenty-five arrives, but it's the farthest of all, so it lands on top and is bumped at once. The bench keeps five, ten and seventeen.
Each push and pop works on a heap of at most k, so it costs log k. That's n log k time and k space. Quickselect averages linear time, but the heap is simpler, and it works on a stream that never ends.
Square, don't root. Keep k seats, bump the farthest. That's K Closest Points to Origin.