Mark As Completed Discussion

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.

Question

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?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

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.

Returning members can login to stop seeing this.