TRT
Sign in
mediumCoreLeetCode#size-k max-heap#squared distance

K closest points to origin

Return the k points nearest the origin with a max-heap of size k keyed by squared distance.

The Runtime Theory Team1 min read
Taught inTop-k and merging streamsPro — members onlyA heap of just k items finds the k largest of a billion in one pass. A heap of k stream heads merges k sorted streams. Two heaps keep a running median. These three patterns cover most heap problems.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inpoints = [[1, 3], [-2, 2]], k = 1

out[[-2, 2]]

inpoints = [[3, 3], [5, -1], [-2, 4]], k = 2

out[[3, 3], [-2, 4]] in any order

inpoints = [[0, 1]], k = 1

out[[0, 1]]

Given points on a plane and k, return the k points closest to the origin, in any order.

Before you code

This is top k smallest, so the heap direction flips: keep a max-heap of the k closest so far, whose root is the farthest of them and the one a new point must beat.

Hints

  1. Compare squared distances, x*x + y*y; the square root doesn't change the order.
  2. In Python, push (-dist, x, y) to simulate a max-heap.
  3. When the heap exceeds k, pop the farthest.

Production & complexity notes

When solving K closest points to origin on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Top-k and merging streams to reinforce the underlying pattern.

What it practices

Choosing the heap direction for a top-k problem, from Top-k and merging streams.

Not started

Sign in to save your learning progress.

Sign in to save