Good evening! Here's our prompt for today.
You are given an array of points
where each point represents a point on the X-Y
plane points[i] = [xi, yi]
. You are also given an integer n
. Find the n
closest points to the origin (0, 0)
.
Your answer should be in descending order of distance (largest to smallest). The answer is guaranteed to be unique (except for the order it is in).
The distance between two points on the
X-Y
plane is the Euclidean distance. It is calculated using the formula,√(x1 - x2)2 + (y1 - y2)2
.

For example, consider two points [1, 1]
and [1, 2]
, and n = 1
. The distance between [1, 1]
and the origin is sqrt(2)
(approximately 1.42
), and the distance between [1, 2]
and the origin is sqrt(5)
(approximately 2.24). sqrt(2)
is the smaller of two numbers, so the point [1, 1]
is closer to the origin, which makes it the answer.
Constraints
1 <= n <= points.length <= 104
-104 < xi, yi < 104
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
console.log('PASSED: ' + "`nClosestPoints([[3, 3], [5, -1], [-2, 4]], 2)` should return `' [[-2, 4], [3, 3]]`");
var assert = require('assert');
​
function nClosestPoints(points, n) {
// add your code here
return;
}
​
​
try {
assert.deepEqual(nClosestPoints([
[1, 3],
[-2, 2]
], 1), [
[-2, 2]
]);
console.log('PASSED: ' + "`nClosestPoints([[1, 3], [-2, 2]], 1)` should return `[[-2, 2]]`");
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(nClosestPoints([
[3, 3],
[5, -1],
[-2, 4]
], 2), [
[-2, 4],
[3, 3]
]);
Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.