FAANGPrep Sprint
K Closest Points to Origin
Find the K closest points to the origin (0, 0).
Problem Understanding
Each points[i] = [xi, yi] is a point on a flat X-Y plane. Return the k of them that lie nearest to the origin (0, 0).
"Nearest" means straight-line (Euclidean) distance, which for a point measured from the origin is √(x² + y²). The k points can come back in any order.
Algorithm Strategy
We want the K smallest distances.
- We can use a Max-Heap of size K.
- Why Max-Heap? Because we want to keep the "smallest" K elements. If the heap gets too big (> K), we want to evict the largest element (the one furthest away) to make room for smaller ones.
Algorithm:
- Initialize a Max-Heap.
- Iterate through all points.
- Calculate squared distance for each point (
x^2 + y^2). We don't need sqrt since it preserves order. - Push (distance, point) to heap.
- If size > k, pop the max element.
- Return the points remaining in the heap.
Interactive Visualization
k = 2 · NODES SHOW x² + y²
EMPTY HEAP
points
empty heap
Kept
0/2
Farthest kept
—
Returned
—
An empty max-heap keyed by distance: the farthest point kept is always on top. It keeps at most k = 2
Next
Read point 0: (3, 3)
Points
k
The plane shows every point. Once the heap holds k, a dashed circle passes through the farthest point kept — a new point has to land inside it to stay. The max-heap beside it is keyed by squared distance.
