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:
heapqis 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; avoidmath.sqrt/math.distin 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.