K Closest Points to Origin – Solution & Complexity
Solution Walkthrough
Step 1: Brute-force baseline
- Compute every distance, sort all
npoints, and take the firstk. - That is correct, but sorting the whole array does more work than necessary when
kis small.
- Compute every distance, sort all
Step 2: Keep only the current best k
- Use a max-heap keyed by
(distance, x, y)so the current worst selected point stays on top. - If a new point is better than that worst point, replace it.
- Use a max-heap keyed by
Step 3: Finish with deterministic ordering
- Heap order is not the same as output order.
- Sort the
kretained points by(distance, x, y)before returning them.
Step 4: Final solution (all languages)
A size-k max-heap keeps selection efficient, then a final sort satisfies the exact judge contract.
Step 5: Complexity summary
- Time:
O(n log k + k log k). - Space:
O(k)besides the returned output.
- Time: