K Closest Points to Origin

Return the k closest points to the origin using a max-heap of size k.

Medium
Time O(n log k) Space O(k)
LeetCode
5 min read
top-k heaps

Problem#

Given points[i] = [xi, yi], return the k points closest to the origin (by Euclidean distance).

Examples#

  • points = [[1,3],[-2,2]], k = 1[[-2,2]]

Constraints#

  • 1 <= k <= points.length <= 10^4.

Approach#

Max-heap of size k keyed by squared distance. Push every point; pop when size > k. The heap ends holding the k smallest.

Solution#

K Closest Points to Origin
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
auto dist = [](const vector<int>& p) {
return (long long)p[0] * p[0] + (long long)p[1] * p[1];
};
priority_queue<pair<long long, int>> pq; // (dist, idx)
for (int i = 0; i < (int)points.size(); ++i) {
pq.push({dist(points[i]), i});
if ((int)pq.size() > k) pq.pop();
}
vector<vector<int>> ans;
while (!pq.empty()) { ans.push_back(points[pq.top().second]); pq.pop(); }
return ans;
}
};

Editorial#

Mirror of the kth-largest-in-stream pattern: a max-heap of size k holds the k smallest candidates seen so far. Compare with squared distance (no sqrt needed — ordering is preserved).

Complexity#

  • Time: O(n log k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.