AlgoDaily

N Points Near Origin

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Question

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.

image

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

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →