</>

973. K Closest Points to Origin

Medium NeetCode 150
Heap / Priority Queue Time O(n log k) Space O(k)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Heap / Priority Queue
Time
O(n log k)
Space
O(k)

Standard Solution (C++)

SummaryGiven a set of 2D points, return the k of them that lie closest to the origin (0,0).

Approach

Max-heap of size k on squared distance. We never need the actual square root since comparing squared distances preserves order.

  • Push each point keyed by xx + yy.
  • Keep only the k smallest by popping the largest whenever the heap exceeds size k.
  • Drain the heap into the result.
class Solution {
public:
    vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
        priority_queue<pair<int, int>> maxHeap; // (dist, index)
        for (int i = 0; i < (int)points.size(); ++i) {
            int d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
            maxHeap.push({d, i});
            if ((int)maxHeap.size() > k) maxHeap.pop();
        }
        vector<vector<int>> res;
        while (!maxHeap.empty()) {
            res.push_back(points[maxHeap.top().second]);
            maxHeap.pop();
        }
        return res;
    }
};
Time O(n log k) Space O(k)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern