arrays
heap
priority-queue
Given points on the 2D plane, return the k points closest to the origin (0, 0) using Euclidean distance.
For this judge, keep the output deterministic: return the chosen points sorted by (squaredDistance, x, y) ascending.
Input / output
- Input:
points: int[][],k: int - Output:
int[][]
You may compare squared distances instead of taking square roots because the relative ordering is the same.
Examples
points = [[1,3],[-2,2]],k = 1returns[[-2,2]]. Squared distances are10and8, so[-2,2]is closer.points = [[3,3],[5,-1],[-2,4]],k = 2returns[[3,3],[-2,4]]. Their squared distances are18,26, and20, so the first and third points are chosen, then sorted by distance.points = [[1,1],[-1,-1],[1,-1]],k = 2returns[[-1,-1],[1,-1]]. All three points have the same squared distance, so tie-break withxand theny.
Constraints
1 <= points.length <= 10^41 <= k <= points.length-10^4 <= x, y <= 10^4
Edge cases
- Distances can tie.
- Negative coordinates are allowed.
kcan equal the number of points.
Target complexity
- Aim for
O(n log k)selection plusO(k log k)final ordering.
Hints
- A max-heap of size
kcan discard the current farthest selected point whenever a better candidate appears. - After the heap finishes, sort the selected
kpoints to satisfy the deterministic output contract.
Follow-up How could quickselect reduce the average selection cost if the output order did not need to be sorted?
Examples
Example 1
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Example 2
Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Example 3
Input: points = [[1,1],[-1,-1],[1,-1]], k = 2
Output: [[-1,-1],[1,-1]]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.