Opening the reading…
Opening the reading…
HEAP (PRIORITY QUEUE) › KTH PATTERN PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A point is closer to the origin when x squared plus y squared is smaller. The square root in the Euclidean distance does not change the ordering, so comparing squared distances gives exactly the same answer without floating-point work. For each point, the real question is whether it belongs among the k smallest distances seen so far.
A max-heap keeps the largest distance among the points currently selected at its top. Add every point, and whenever the heap grows to k + 1, remove that top point. The removed point is the least useful one: it is farther from the origin than every point still retained. After the scan, the heap contains precisely the k closest points, in no required order.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n log k) | Each of the n points is inserted into a heap containing at most k entries, and an oversized heap performs one removal costing O(log k). Extracting the final k entries costs O(k log k), which is covered by O(n log k) because k <= n. |
| Space | O(k) extra | The heap stores at most k entries, and the result is required output and is excluded from the extra-space bound. When k = n, the heap reaches O(n), which is the worst possible input setting for this bound. |
#include <vector>
#include <queue>
#include <utility>
using namespace std;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
auto cmp = [](const pair<int, pair<int, int>>& a,
const pair<int, pair<int, int>>& b) {
return a.first < b.first;
};
priority_queue<
pair<int, pair<int, int>>,
vector<pair<int, pair<int, int>>>,
decltype(cmp)
> pq(cmp);
for (const auto& point : points) {
int x = point[0];
int y = point[1];
int distance = x * x + y * y;
pq.push({distance, {x, y}});
if (static_cast<int>(pq.size()) > k) {
pq.pop();
}
}
vector<vector<int>> result;
while (!pq.empty()) {
auto entry = pq.top();
pq.pop();
result.push_back({entry.second.first, entry.second.second});
}
return result;
}
};The comparator makes the heap a max-heap by distance: an entry with a larger first value rises to the top. That top entry is intentionally the point to discard when size exceeds k. The removal must happen during the scan, not after storing every point, because bounding the heap is what changes the memory usage from O(n) to O(k).
You can partition the points around the position k instead of maintaining a heap. nth_element rearranges the array so that the first k points are no farther than the remaining points, without fully sorting either side. This is an optimization on average, reducing the time to O(n) and using O(1) extra working space, but its worst-case time can be O(n squared) depending on the partition behavior. It also changes the input array.
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
auto distance = [](const vector<int>& point) {
int x = point[0];
int y = point[1];
return x * x + y * y;
};
nth_element(
points.begin(),
points.begin() + k,
points.end(),
[&](const vector<int>& a, const vector<int>& b) {
return distance(a) < distance(b);
}
);
return vector<vector<int>>(points.begin(), points.begin() + k);
}
};