K Closest Points to Origin - Problem
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)² + (y1 - y2)²).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Input & Output
Example 1 — Basic Case
$
Input:
points = [[1,1],[3,3],[1,3]], k = 2
›
Output:
[[1,1],[1,3]]
💡 Note:
Distance from origin: [1,1] has distance √2, [3,3] has distance √18, [1,3] has distance √10. The 2 closest are [1,1] and [1,3].
Example 2 — Larger Input
$
Input:
points = [[3,3],[5,-1],[-2,4]], k = 2
›
Output:
[[-2,4],[3,3]]
💡 Note:
Distances: [3,3] → √18, [5,-1] → √26, [-2,4] → √20. The 2 closest are [-2,4] and [3,3].
Example 3 — Single Point
$
Input:
points = [[0,1]], k = 1
›
Output:
[[0,1]]
💡 Note:
Only one point exists, so it must be the closest.
Constraints
- 1 ≤ k ≤ points.length ≤ 104
- -104 ≤ xi, yi ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Points
Points plotted on coordinate plane with origin
2
Calculate Distances
Compute Euclidean distance from each point to origin
3
Select K Closest
Return the k points with smallest distances
Key Takeaway
🎯 Key Insight: Use squared distances to avoid expensive square root calculations, and choose the right algorithm based on input size and k value.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code