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
K Closest Points to Origin: Find 2 Closest from [[1,1],[3,3],[1,3]]XYOrigin (0,0)[1,1]d = √2 ≈ 1.41[3,3]d = √18 ≈ 4.24[1,3]d = √10 ≈ 3.16K=2 Closest PointsSelected: [1,1] (d≈1.41) and [1,3] (d≈3.16)
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.
Asked in
Amazon 68 Facebook 45 Google 32 Microsoft 28
125.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen