Skip to the solution
MediumDSA9 min read

How do you find the k closest points to the origin?

1.1k views

The problem

Question presented to candidate: "You are given a list of points on a plane as [x, y] pairs and a number k. Return the k points closest to the origin (0, 0). Write it in Python and explain the complexity. Any order is fine, but tell me how you would make it deterministic."

What a strong answer should cover:

  • Compare squared distances xยฒ + yยฒ: same order as the real distance, exact integers, no sqrt.
  • A max-heap of size k (the root is the farthest kept point): O(n log k) time, O(k) space, one pass.
  • Quickselect on the squared distance: average O(n), worst O(nยฒ), reorders the list; sorting is the O(n log n) baseline.
  • Ties: a composite key (distance, x, y) makes the output deterministic.
  • Python specifics: heapq is a min-heap, so push negated keys (-d, -x, -y) for a max-heap; heapq.nsmallest(k, points, key=...) is the one-liner; Python integers never overflow, so large coordinates are safe; avoid math.sqrt/math.dist in the comparison.

Clarifying questions expected:

  • How large can the coordinates be, and how should ties be ordered?
  • Is k small compared with n, and may I reorder the input?

Code / implementation expected: Yes โ€” a size-k heap with heapq (negated keys) in Python, plus the idea of quickselect.

  • heap
  • geometry

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonK closest points with a size-k max-heap on squared distance
PythonSorting vs heap vs quickselect on 50,000 points, and 64-bit squared distances

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 43 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the 0/1 knapsack problem?

Continue