Skip to content

K Closest Points to Origin

LeetCode

01 · Question

Given an array of points where points[i] = [xi, yi] and an integer k, return the k closest points to the origin (0, 0).

02 · Solution

Reference solution

1import heapq
2
3def kClosest(points: List[List[int]], k: int) -> List[List[int]]:
4 heap = []
5 for x, y in points:
6 d = x*x + y*y
7 heapq.heappush(heap, (d, x, y))
8 res = []
9 for _ in range(k):
10 _, x, y = heapq.heappop(heap)
11 res.append([x, y])
12 return res