Skip to main content

K Closest Points to Origin

MediumPremium

Given an array points where points[i] = [x, y] is a point on a plane, and an integer k, return the k points closest to the origin (0, 0).

Distance is the usual straight-line distance, sqrt(x^2 + y^2). Return the points in any order. The tests are built so that the k closest points are unique.

Example 1

Input: points = [[1, 3], [-2, 2]], k = 1 Output: [[-2, 2]]

[1, 3] is sqrt(10) from the origin and [-2, 2] is sqrt(8), so [-2, 2] is closer.

Example 2

Input: points = [[3, 3], [5, -1], [-2, 4]], k = 2 Output: [[3, 3], [-2, 4]]

The squared distances are 18, 26 and 20, so the two closest are [3, 3] and [-2, 4]. [[-2, 4], [3, 3]] is also accepted.

Constraints

  • 1 <= k <= points.length <= 10^4
  • -10^4 <= x, y <= 10^4