Overview
Given an array of points points where points[i] = [xi, yi] and an integer k, return the k closest points to the origin (0, 0). Distance is Euclidean. Return in any order.
Constraints
1 <= k <= points.length <= 10,000-10,000 <= xi, yi <= 10,000
Examples
kClosest([[1,3],[-2,2]], 1); // => [[-2,2]] (distance √8 < √10) kClosest([[3,3],[5,-1],[-2,4]], 2); // => [[3,3],[-2,4]]
Solution
Reveal solution
function kClosest(points, k) {
points.sort((a, b) => (a[0]*a[0] + a[1]*a[1]) - (b[0]*b[0] + b[1]*b[1]));
return points.slice(0, k);
}Resources
k-closest-points-to-origin.js
K Closest Points to Origin
mediumcodingAlgorithmsSorting
Overview
Given an array of points points where points[i] = [xi, yi] and an integer k, return the k closest points to the origin (0, 0). Distance is Euclidean. Return in any order.
Constraints
1 <= k <= points.length <= 10,000-10,000 <= xi, yi <= 10,000
Examples
kClosest([[1,3],[-2,2]], 1); // => [[-2,2]] (distance √8 < √10) kClosest([[3,3],[5,-1],[-2,4]], 2); // => [[3,3],[-2,4]]
Solution
Reveal solution
function kClosest(points, k) {
points.sort((a, b) => (a[0]*a[0] + a[1]*a[1]) - (b[0]*b[0] + b[1]*b[1]));
return points.slice(0, k);
}Resources
NameTopicDifficulty
103 of 103 problems