K Closest Points to Origin

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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: √(x² + y²).

You may return the answer sorted by distance (closest first). If two points have the same distance, sort by x-coordinate, then by y-coordinate.

Examples

Example 1:

Input: points = [[1,3],[-2,2]], k = 1

Output: [[-2,2]]

Explanation: The distance from (1, 3) to the origin is √10. The distance from (-2, 2) to the origin is √8. Since √8 < √10, (-2, 2) is the closest point.

Example 2:

Input: points = [[3,3],[5,-1],[-2,4]], k = 2

Output: [[3,3],[-2,4]]

Explanation: The distances are √18, √26, and √20. The two closest points are (3, 3) at √18 and (-2, 4) at √20.

Constraints

  • 1 <= k <= points.length <= 10⁴
  • -10⁴ <= xi, yi <= 10⁴
Source: Top K Elements pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle