Problem 457789 · medium · Phase 04 Non-Linear Data Structures

K Closest Points to Origin

heap · max-heap · geometry

Given a list of points [x, y] on a plane and an integer k, return the k points closest to the origin (0, 0), measured by Euclidean distance. The answer is guaranteed to be unique (no ties at the boundary) and may be returned in any order, as a list of [x, y] lists.

Examples

Input:  points = [[1, 3], [-2, 2]], k = 1
Output: [[-2, 2]]
Explanation: distance^2 of [1, 3] is 10, of [-2, 2] is 8.
Input:  points = [[3, 3], [5, -1], [-2, 4]], k = 2
Output: [[3, 3], [-2, 4]]

Constraints

  • 1 <= k <= len(points) <= 10**4
  • -10**4 <= x, y <= 10**4

Goals

  • Simulate a max-heap with heapq by negating the key
  • Compare distances without a square root
  • Keep the k best candidates in a bounded heap while scanning a list
Starting Python…