Heap / Priority Queue
Medium
K Closest Points to Origin
Find the K closest points to the origin (0, 0).
10 min read
Solve on LeetCodeProblem 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:
- 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
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.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases
- Solution
- Complexity Analysis
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.
