Return the points nearest to the origin from a list of 2D points.
Problem
You are given an array of points in a 2D plane, where each point is represented as [x, y], and an integer k.
Your task is to return any k points whose Euclidean distance to the origin (0, 0) is smallest among all points in the array.
The distance of a point [x, y] from the origin is determined by (you do not need to compute the square root).
If multiple points are tied for distance, any valid set of k points is acceptable.
Input Format
- An integer array
points, wherepoints[i] = [x_i, y_i] - An integer
k
Output Format
- Return an array containing any
kpoints with the smallest distance to the origin
Constraints
1 <= k <= points.lengthpoints.lengthis at least1- Coordinates may be positive, negative, or zero
Hints
- Comparing squared distances is enough.
- Think about how to efficiently keep track of the current closest
kpoints while scanning the array.
Input Format
points: list of 2D integer coordinatesk: number of closest points to return
Output Format
- An array of exactly
kpoints selected from the input
Constraints
1 <= k <= points.length- Each point has two integer coordinates
- Return any valid answer when ties exist
Example 1
Input
points = [[1,3],[-2,2]], k = 1
Output
[[-2,2]]
Explanation
The squared distances are 10 and 8, so [-2,2] is closer to the origin.
Example 2
Input
points = [[3,3],[5,-1],[-2,4]], k = 2
Output
[[3,3],[-2,4]]
Explanation
The squared distances are 18, 26, and 20. The two closest points are [[3,3],[-2,4]] in any order.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.