K Nearest Points to Origin
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Tests heap-based selection and distance computation to efficiently find the k points closest to the origin in 2D space.
You are given a list of n points in 2D space, where each point is represented as [x, y], and a positive integer k where 1 ≤ k ≤ n.
Find the k points that are nearest to the origin (0, 0) measured by Euclidean distance. You may return the points in any order.
When comparing distances, you may use squared Euclidean distance (avoiding the square root) since it preserves the same ordering.
If two points have the same distance from the origin, either may be included in the result.
Constraints
1 ≤ k ≤ points.length ≤ 10⁴- Each point
[x, y]has integer coordinates where-10⁴ ≤ x, y ≤ 10⁴ - The origin
(0, 0)may appear in the input - Return the k nearest points in any order
Examples
Example 1
Input: k_nearest_points([[1, 3], [-2, 2]], 1)
Output: [[-2, 2]]
Example 2
Input: k_nearest_points([[3, 3], [5, -1], [-2, 4]], 2)
Output: [[-2, 4], [3, 3]]
Example 3
Input: k_nearest_points([[0, 0], [1, 1], [-1, -1], [2, 0]], 3)
Output: [[-1, -1], [0, 0], [1, 1]]
Hints
Hint 1
Compare squared distances (x² + y²) instead of taking square roots—it's faster and preserves ordering.
Hint 2
A simple solution sorts all n points by distance, but can you do better when k is much smaller than n?
Hint 3
Maintain a max-heap of size k containing the closest points seen so far. When a closer point arrives and the heap is full, evict the farthest.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task requires selecting the k smallest elements by distance from a collection of n points. A straightforward solution would sort all points by their distance from the origin and take the first k, running in O(n log n) time. However, when k is significantly smaller than n, we can do better.
Use a max-heap of size k to track the k nearest points encountered so far. In this heap, the root always holds the point with the largest distance among the k candidates. As you scan through the points:
- If the heap contains fewer than k points, insert the current point.
- If the heap is full and the current point is closer than the heap's root, replace the root with the current point.
By the end, the heap contains exactly the k nearest points.
Why Squared Distance
Computing x² + y² instead of √(x² + y²) avoids floating-point arithmetic and is faster. Since the square root function is monotonic, comparing squared distances yields the same ordering as comparing true Euclidean distances.
Max-Heap via Negation
Python's heapq implements a min-heap, but we need max-heap behavior (the farthest point at the root). Store tuples with negated distance: (-distance, -i, x, y). The smallest tuple by lexicographic order will be the one with the largest distance. Including the negated index -i ensures that when distances tie, the earlier point in the input is kept, making the output deterministic.
Why It Works
After processing each point, the invariant holds: the heap contains the k closest points from those seen so far. When a new point arrives:
- If it is closer than the current farthest kept point (the root), it belongs in the top k, and the root should be evicted.
- If it is farther or equal, it does not improve the current selection.
The comparison entry > heap[0] leverages tuple ordering. A strictly closer point has a larger negated distance, so the comparison succeeds. When distances tie, the negated index breaks the tie, and since indices increase, the new point's tuple will be smaller, preventing replacement. This keeps the earlier point, ensuring deterministic output.
Complexity
- Time: O(n log k). Each of the n points requires at most one heap operation (insert or replace), each costing O(log k).
- Space: O(k) for the heap.
This is better than O(n log n) sorting when k is small relative to n, which is common in practice (e.g., finding the 10 nearest points among a million).
Full Solution
import heapq
from typing import List
def k_nearest_points(points: List[List[int]], k: int) -> List[List[int]]:
# Use a max-heap of size k by negating distances.
# The root represents the farthest point currently kept.
# Including index ensures deterministic behavior when distances tie.
heap = []
for i, point in enumerate(points):
x, y = point
distance = x * x + y * y
entry = (-distance, -i, x, y)
if len(heap) < k:
heapq.heappush(heap, entry)
elif entry > heap[0]:
heapq.heapreplace(heap, entry)
return [[entry[2], entry[3]] for entry in heap]