K Closest Points to Origin
1 approach, code in every language
Problem description
You are given an array `points` where `points[i] = [xi, yi]` is a point on the 2D plane, along with an integer `k`.
Return the `k` points that are closest to the origin `(0, 0)`, measured by Euclidean distance sqrt(x^2 + y^2).
The answer may be returned in any order, and it is guaranteed to be unique except for that ordering.
Example 1
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
The distance of [1,3] is sqrt(10) and of [-2,2] is sqrt(8). Since sqrt(8) < sqrt(10), the single closest point is [-2,2].
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; the two smallest belong to [3,3] and [-2,4]. Any order of these two is accepted.
Constraints
1 <= k <= points.length <= 10^4-10^4 <= xi, yi <= 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Nearest Survey Stakes is our own problem on the technique behind K Closest Points to Origin: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free