K Closest Points to Origin

LeetCode

LeetCode: https://leetcode.com/problems/k-closest-points-to-origin/

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

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
1
0
3
1
-2
2
2
3
2
4
-2
5
k=1
Step 1 / 2
Step 1:
Push all points into a min-heap keyed by squared distance.
Focus: select @ [0, 1]
k=1