As asked
Given a list of 2D points and an integer K, return the K points closest to the origin (0, 0). You do not need to return them in sorted order. Now walk me through the time complexity of each approach you can think of.
Sample answer outline
Three viable approaches: sort all points by Euclidean distance in O(n log n), use a max-heap of size K in O(n log K) which is better when K is much smaller than n, or use QuickSelect (partition-based) for O(n) average time. A strong answer compares all three and picks the right one based on the constraints given. The candidate should also note they can compare squared distances to avoid the sqrt computation.
Reference implementation (python)
import heapq
def k_closest(points: list[list[int]], k: int) -> list[list[int]]:
# Max-heap of size k: negate distance to simulate max-heap with Python's min-heap
heap = []
for x, y in points:
dist = -(x*x + y*y) # negated squared distance
heapq.heappush(heap, (dist, x, y))
if len(heap) > k:
heapq.heappop(heap)
return [[x, y] for _, x, y in heap]Expect these follow-ups
- What if K were very large, close to N?
- How would you handle streaming points arriving one at a time?