Heap / Priority Queue
Medium

K Closest Points to Origin

Find the K closest points to the origin (0, 0).
Problem Understanding

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)^2 + (y1 - y2)^2).

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
Step 1 / 1
Empty Heap

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep