Browse curriculum

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:

  1. Initialize a Max-Heap.
  2. Iterate through all points.
  3. Calculate squared distance for each point ( x^2 + y^2 ). We don't need sqrt since it preserves order.
  4. Push (distance, point) to heap.
  5. If size > k, pop the max element.
  6. Return the points remaining in the heap.

Interactive Visualization

k = 2 · NODES SHOW x² + y²

EMPTY HEAP

points

(3, 3)
(5, -1)
(-2, 4)
(1, 1)
(0, -2)

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

2

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.