Practice · Heap · 3 of 5

Closest Points to the Origin

You are given points, a list of points on a plane, each written [x, y], and an integer k. Return the k points closest to the origin (0, 0), measured by ordinary straight-line distance, √(x² + y²).

Return the points in any order. The tests make sure the answer is unique: the k-th closest point is always strictly closer than every point left out. The same point may appear more than once in points; each copy counts as a separate point.

Example 1

Input
points = [[2, -1], [-3, 0], [1, 4]], k = 1
Output
[[2, -1]]
The squared distances are 5, 9 and 17, so [2, -1] is closest.

Example 2

Input
points = [[0, 5], [4, 4], [-1, -2], [3, -3]], k = 2
Output
[[-1, -2], [3, -3]]
The squared distances are 25, 32, 5 and 18. The two smallest are 5 and 18; [[3, -3], [-1, -2]] is right too.

Constraints

  • 1 ≤ k ≤ length of points ≤ 10⁴
  • −10⁴ ≤ x, y ≤ 10⁴
Brush up firstHeap visualiser