K Closest Points to Origin

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance, i.e., √(x1 - x2)^2 + (y1 - y2)^2.

You may return the answer in any order. The answer is guaranteed to be unique except for the order that it is in.

Example 1
Inputpoints = [[1,3],[-2,2]], k = 1
Output[[-2,2]]
The distance from (1, 3) to the origin is sqrt(10), while the distance from (-2, 2) is sqrt(8), so (-2, 2) is the closest point.
Example 2
Inputpoints = [[3,3],[5,-1],[-2,4]], k = 2
Output[[3,3],[-2,4]]
The answer [[-2,4],[3,3]] would also be accepted because order does not matter.

Constraints

  • 1 <= k <= points.length <= 10^4
  • -10^4 <= xi, yi <= 10^4

Asked at 15 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate