K Closest Points to Origin
Pick the k points nearest to (0, 0) with a max-heap of size k that always throws out the farthest point.
The problem
You get an array of points on a plane, points[i] = [x, y], and an integer k. Return the k points closest to the origin (0, 0), measured by straight-line distance, in any order. You can assume the answer is unique apart from its order.
Input points = [[3, 4], [-1, 2], [5, -1], [0, -2]], k = 2
Output [[-1, 2], [0, -2]]
The squared distances are 25, 5, 26 and 4, so the two smallest belong to [0, -2] and [-1, 2].
Input points = [[2, 2], [-3, 0]], k = 1
Output [[2, 2]]
2 * 2 + 2 * 2 = 8 is less than 9, so [2, 2] is closer.
Key constraint: Up to 10,000 points, and you only need the k closest, not a full ordering by distance.
How to spot the pattern
- You need the k best items by a score (distance), in any order.
- k can be much smaller than the number of points.
The idea
Keep the k closest points seen so far in a max-heap keyed by distance, so the farthest of them sits on top, ready to be thrown out. Push each new point, and if the heap now holds more than k points, pop the farthest. Squared distance x * x + y * y orders points exactly like real distance, so you never need a square root.
Brute force: Sort all points by distance and take the first k, which costs O(n log n).
Step by step
- 1Create an empty max-heap ordered by
x * x + y * y. - 2Push each point onto the heap.
- 3Whenever the heap holds more than
kpoints, pop the one on top, which is the farthest. - 4Return the points left in the heap.
See the pattern move
The heaps and top k pattern on a small example. Step through it, or press play.
Code
import heapq
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
# heapq is a min-heap, so store negated distances to keep the farthest point on top.
heap = [] # (-squared distance, x, y)
for x, y in points:
heapq.heappush(heap, (-(x * x + y * y), x, y))
if len(heap) > k:
heapq.heappop(heap) # drop the farthest
return [[x, y] for _, x, y in heap]Complexity
Time
O(n log k)
Space
O(k)
Each point passes through a heap that never holds more than k + 1 entries.
Watch out for
- Using a min-heap while keeping only k points, which throws away the closest points instead of the farthest.
- Taking square roots: it is slower and floating-point rounding can make equal distances compare differently; compare squared distances.
- Forgetting that squares can get big: here x * x + y * y is at most 200,000,000, which fits in a 32-bit int, but larger coordinates would need 64 bits.
Follow-up questions
Can you do it in O(n) on average?
Quickselect on the squared distances: partition around a random pivot and keep going only into the side that holds the k-th closest point. When it finishes, the first k points are the answer.
What if the points arrive as a stream?
The heap version already works on a stream: keep a max-heap of size k and update it as each point arrives, so the current answer is always the heap's contents.
In Hinglish
Size k ka max-heap rakho jismein sabse door wala point top par ho. Naya point daalo, k se zyada ho jaayein toh sabse door wala nikaal do.