Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the k points closest to the origin (ties broken by smaller index).

Problem: Return the k points closest to the origin (ties broken by smaller index).
import heapq
pts = [(3, 3), (5, -1), (-2, 4), (1, 1), (0, -2)]
print(heapq.nsmallest(3, range(len(pts)), key=lambda i: pts[i][0]**2 + pts[i][1]**2))
What is printed?
  1. A. [3, 4, 2]
  2. B. [4, 3, 0]
  3. C. [3, 4, 0]
  4. D. [0, 3, 4]

Correct answer: C. [3, 4, 0]

Squared distances: 18, 26, 20, 2, 4 → the three smallest are index 3 (2), index 4 (4) and index 0 (18); (−2, 4) at 20 just misses. Comparing squared distances avoids sqrt and floating error. nsmallest keeps a size-k heap: O(n log k); quickselect gives O(n) average.

More Coding Interview Problems questions

Exams that ask this topic