Find the K Closest Points to the Origin
Company: Asana
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: Select the k points closest to the origin from a much larger set of distinct integer coordinates. Use squared distance and deterministic coordinate tie-breakers, then return the chosen points in ranked order.
Constraints
- 1 <= k <= len(points) <= 200,000
- Points are distinct integer coordinate pairs.
- -10^9 <= x, y <= 10^9
- Rank by (squared distance, x, y) and return points in that order.
Examples
Input: ([[1, 3], [-2, 2], [2, -2]], 2)
Expected Output: [[-2, 2], [2, -2]]
Explanation: Equal squared distance is broken by x then y.
Input: ([[0, 0]], 1)
Expected Output: [[0, 0]]
Explanation: The origin is the only point.
Hints
- Keep only the best k ranks in a max-heap whose root is the worst selected point.
- Use wide integer arithmetic for squared distances; JavaScript can compare them as BigInt.
- Sort the retained k points by the required rank before returning them.