#973
Medium Algorithms K closest points to origin
Array Math Divide and Conquer Geometry Sorting Heap (Priority Queue) Quickselect
68.8% acceptance
Feb 25, 2026
9033
338
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn k_closest(mut points: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
points.sort_by_key(|p| p[0]*p[0] + p[1]*p[1]);
points.truncate(k as usize);
points
}
}