K Closest Points to Origin
Max-heap
Problem
We have a list of points
on the plane. Find the K
closest points to the origin (0, 0)
.
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
For example:
Thought Process
Since we are looking for the K closest points to the origin, we need to know what the furthest points from the origin are so we can discard them in place for the closest points (because our for-loop will skip any points/their distance that may be greater i.e. further away from the origin than the other K elements.) This is why we use a max heap.
We use the Euclidean distance formula to calculate the distance.
To associate points with their distances, in the max heap we will store the distance with their points.
In each iteration of our for-loop from K we are saying: "Ok, here is the furthest point from the origin we have thus far in our heap, is the current distance smaller than this? If so, then pop this furthest point at heap[0] and insert this new point."
Solution
Key Points
Using a max heap in order to know what the furthest points from the origin (large distances) are so we can discard them
Storing the distances and points together in pairs in the heap
Time Complexity
Time: as we are iterating points and pushing them into the heap
Space:
Last updated
Was this helpful?