K Closest Points to Origin
A medium Heap problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Heap
- Sheets
- 2
- Core for
- 9 roles
- Platform
- LeetCode
The problem
Given an array of points on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points is the Euclidean distance. You may return the answer in any order, and the answer is guaranteed to be unique (except for the order).
Example 1
- Input
- points = [[1,3],[-2,2]], k = 1
- Output
- [[-2,2]]
- Why
- The distance of (1,3) from origin is sqrt(10) and the distance of (-2,2) is sqrt(8). Since sqrt(8) < sqrt(10), (-2,2) is closer and is the answer.
Example 2
- Input
- points = [[3,3],[5,-1],[-2,4]], k = 2
- Output
- [[3,3],[-2,4]]
- Why
- Distances are sqrt(18), sqrt(26), and sqrt(20). The two closest are (3,3) with sqrt(18) and (-2,4) with sqrt(20).
Constraints
- 1 <= k <= points.length <= 10^4
- -10^4 <= points[i][0], points[i][1] <= 10^4
How to think about it
Updated 2026-09-09Comparing Euclidean distances never requires taking square roots: x^2 + y^2 preserves the exact relative ordering while avoiding floating-point inaccuracy. Because you only need the k closest, maintaining a boundary of the worst among your best allows filtering out distant points immediately.
Approaches, worst first
Full sort by distance
time O(n log n) · space O(n)
Compute squared distances for every coordinate, sort the entire array ascending, and slice the first k entries. Works in one pass of sorting, but pays to sequence all n points when only k are needed.
Bounded max-heap of size k
time O(n log k) · space O(k)
Keep a max-heap of size k keyed by squared distance. For each point, compare against the root: if closer, pop the furthest keeper and insert the newcomer. The heap retains only the k closest seen so far.
Quickselect partitioningWrite this one
time O(n) · space O(1)
Partition points around a pivot distance recursively until the pivot index lands precisely at k. Gives an unordered prefix containing the exact k closest elements without sorting them internally.
Where people lose marks · 3
- Calling Math.sqrt on every coordinate pair. Squaring avoids floating-point roundoff errors and eliminates an expensive mathematical function without altering relative ordering.
- Using a min-heap to collect the k closest instead of a max-heap. A min-heap capped at k would evict the closest points instead of the furthest ones.
- Forgetting that coordinates can be negative. Always square x and y or preserve signs during multiplication so distances never turn negative or miscalculated.
The theory behind it
Heap — the ground this problem stands on. All Heap problems
What Heap is
A heap is a specialized tree that keeps only the single most extreme item at the very top. In a min-heap, every parent node is smaller than its children, so the smallest element in the entire collection sits immediately at the root. Unlike a binary search tree, a heap does not keep all items in full sorted order. It maintains only a partial order, making it fast at giving you the single smallest or largest item without spending time sorting everything else.
When to reach for it
Reach for a heap when a problem asks for the top k largest elements, the kth smallest value, or a running median from a stream of numbers. Signals include phrases like continuously finding the cheapest item, merging k sorted linked lists, or scheduling tasks with priorities. Whenever you need repeated access to the minimum or maximum value while items are added and removed dynamically, a priority heap is the tool.
How the pattern works
To find the k largest elements, keep a min-heap of fixed size k. Push incoming numbers into the heap; whenever the heap size grows past k, pop the top item, which is the smallest among them. After processing all elements, only the k largest remain. For a running median, balance two heaps: a max-heap holding the smaller half of numbers and a min-heap holding the larger half. In code, heaps are stored compactly as flat arrays where a node at index i has children at indices 2i plus 1 and 2i plus 2.
What each operation costs
| Operation | Time |
|---|---|
| read the minimum or maximum element | O(1) |
| insert a new element and sift into position | O(log n) |
| remove the top element and sift down | O(log n) |
| build a heap from an array of n items | O(n) |
What usually goes wrong with Heap
- Using a max-heap instead of a min-heap when keeping the k largest elements, causing the largest values to be evicted while small items stay behind.
- Assuming that extracting elements by iterating over the backing array yields sorted order, without popping items from the heap one by one.
- Forgetting that standard language libraries provide a min-heap by default, leading to wrong answers when a max-heap was required.
Which roles need this problem
Heap is a core topic for these 9 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 11 more roles, including SDE / Backend Engineer, Data Engineer, ML Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Heap problems
Problem set and role mapping as of .