PracticeNeetCode ↗LeetCode ↗
Given a list of points on the X-Y plane and an integer k, return the k points closest to the origin (0, 0), in any order.
k avoids sorting the entire list: it always evicts the farthest of the current top-k candidates.heapq is min-only, so negate the distance to make the heap behave like a max-heap.dist = x*x + y*y and push (-dist, x, y).k, pop the top — the currently farthest of the kept points.k closest — return them.Time: O(n log k) — Space: O(k)
import heapq
def kClosest(points: list[list[int]], k: int) -> list[list[int]]:
heap = []
for x, y in points:
dist = x * x + y * y
heapq.heappush(heap, (-dist, x, y))
if len(heap) > k:
heapq.heappop(heap)
return [[x, y] for _, x, y in heap]How the solution above works, piece by piece.
dist = x*x + y*y: the squared distance. The square root isn't needed because it doesn't change which point is closer.(-dist, x, y): negating makes Python's min-heap act as a max-heap, so the farthest point is on top.Running it on points = [[1, 3], [-2, 2]], k = 1: