SDE & MLE Prep

973. K Closest Points to Origin

Problem

Return the k points closest to the origin (by Euclidean distance), in any order. The answer is unique up to order.

Example: points = [[3,3],[5,-1],[-2,4]], k = 2 → [[3,3],[-2,4]]

Constraints: up to 10⁴ points.

Keep a max-heap of size k on squared distance; evict the farthest. (Quickselect gives average O(n).)

Complexity: O(n log k).

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        h = []
        for x, y in points:
            heappush(h, (-(x * x + y * y), x, y))
            if len(h) > k:
                heappop(h)
        return [[x, y] for _, x, y in h]