v9.1.1
Menu

K Closest Points to Origin

mediumFREEMath & GeometryUber DSA

Given an array of points on the X-Y plane, return the k closest points to the origin (0, 0).

Input: first line = points as x:y comma-separated, second = k. Output each point on a separate line.

Example

Input
1:3,-2:2
1
Output
-2 2
Reasoning
  • The input points are parsed as (1, 3) and (-2, 2) from the string "1:3,-2:2".
  • The distance of each point to the origin is calculated using the Euclidean distance formula: d=x2+y2d = \sqrt{x^2 + y^2}. For the given points, the distances are 12+32=10\sqrt{1^2 + 3^2} = \sqrt{10} and (−2)2+22=8\sqrt{(-2)^2 + 2^2} = \sqrt{8}.
  • The point with the smallest distance to the origin is selected, which is (-2, 2) since 8<10\sqrt{8} < \sqrt{10}.
  • The selected point is output as "-2 2", which matches the given output format.

Constraints

  • 1 <= k <= points.length <= 10^4
  • -10^4 <= x, y <= 10^4

Learn this in

More from Uber DSA

solution.py

Test results

Sign in to run your code against the test cases.