FastPrepK Closest Points to the Origin

K Closest Points to the Origin

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Each row of points is a two-dimensional integer point [x, y]. Return the k points closest to the origin (0, 0) by Euclidean distance. Compare squared distances x² + y²; taking square roots is unnecessary.

For this exercise, return the selected points in their original input order. The selected set is unique for every valid input, so no boundary tie needs to be broken.

Function

kClosest(points: int[][], k: int) → int[][]

Examples

Example 1

points = [[1,3],[-2,2]]k = 1return = [[-2,2]]

The squared distances are 10 and 8, so only the second point is selected.

Example 2

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

The squared distances are 18, 26, and 20. The first and third points are closest.

Example 3

points = [[1,1],[0,1],[8,0]]k = 2return = [[1,1],[0,1]]

Both first points are selected; the returned rows retain input order even though the second point is nearer.

Constraints

  • 1 <= k <= points.length <= 10000.
  • Each point has exactly two integer coordinates between -10000 and 10000.
  • The set of the k closest points is unique.

More Meta problems

See Meta hiring insights
public int[][] kClosest(int[][] points, int k) {
    // Write your code here.
}
points[[1,3],[-2,2]]
k1
expected[[-2,2]]
Checking account…