K Closest Points to Origin – Solution & Complexity
Solution Walkthrough
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.
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.
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.
4. Final solution (all languages)
A size-k max-heap keeps selection efficient, then a final sort satisfies the exact judge contract.
5. Complexity summary
- Time:
O(n log k + k log k). - Space:
O(k)besides the returned output.