Medium · Size-K Heap
Understand → Visualise → Practice.
Return the k points closest to the origin, breaking ties by x then y.
Keep a max-heap of size k keyed by distance. A new point replaces the farthest kept point only if it is closer, so the heap always holds the k closest seen so far.
Compare x² + y²; the square root doesn't change the order.
Push each point; if the heap exceeds k, pop the farthest (ties broken by larger x, then larger y).
Return the kept points sorted by distance, then x, then y.
O(n log k) time and O(k) space.
Sorting everything works but is O(n log n); the heap is better when k is much smaller than n.
Read the full guide first: Heaps and Priority Queues.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.