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: [[3,3],[-2,4]]
💡 Note: Distances: [3,3] → √18, [5,-1] → √26, [-2,4] → √20. The 2 closest are [3,3] and [-2,4].
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 INPUT X Y 1 2 3 1 3 Origin [1,1] [3,3] [1,3] points = [[1,1],[3,3],[1,3]] k = 2 Find 2 closest to origin ALGORITHM STEPS 1 Calculate Distances dist = sqrt(x² + y²) 2 Use Max-Heap (size k) Keep k smallest distances 3 Compare and Replace If dist < heap top, replace 4 Extract Results Return heap contents Distance Calculations [1,1]: sqrt(1+1) = 1.41 [3,3]: sqrt(9+9) = 4.24 [1,3]: sqrt(1+9) = 3.16 Sorted: 1.41 < 3.16 < 4.24 Keep k=2 smallest FINAL RESULT [1,1] d=1.41 [1,3] d=3.16 [3,3] OUTPUT [[1,1], [1,3]] 2 closest points OK - Verified! Time: O(n log k) Space: O(k) Key Insight: Using a max-heap of size k is optimal because we only need the k smallest distances. We can compare x² + y² instead of sqrt(x² + y²) to avoid expensive square root calculations. Alternative: QuickSelect algorithm achieves O(n) average time complexity. TutorialsPoint - K Closest Points to Origin | Optimal Solution (Max-Heap)
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