#973

K Closest Points to Origin

Medium Max-heap of size k

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the k points closest to (0, 0), in any order.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the k points nearest to (0, 0).

Why this works: a max-heap of size k by distance; when a closer point comes, the farthest of the kept ones leaves.

Example: [[1,3], [-2,2]], k = 1

distances 10 and 8 → keep [-2, 2]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a min-heap of all n points and polling k times — O(n log n), more memory.

Solve on LeetCode ↗
Complexity
  • Time: O(n log k).
  • Space: O(k).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon