Menu
CoddyTech

K Closest Points to Origin

MediumHeapSortingpython iconjava iconcpp iconc iconjs icon+10

You get n points on a plane: point i is (xs[i], ys[i]). Return the k points closest to the origin (0, 0), each as a pair [x, y].

Order the answer by distance from the origin, nearest first. Points at the same distance go by smaller x first, then by smaller y. A point listed more than once counts once per copy.

Function

kClosest(xs: integer-array, ys: integer-array, k: integer) → integer-2d-array
xsinteger-array
the x coordinate of each point
ysinteger-array
the y coordinate of each point
kinteger
how many points to return
Returnsinteger-2d-array
the k closest points as [x, y] pairs, nearest first, ties by x and then y

Constraints

  • n == xs.length == ys.length
  • 1 ≤ k ≤ n ≤ 5000
  • -104 ≤ xs[i], ys[i] ≤ 104
  • Points may repeat; each copy is a separate point.

Examples

Input
xs = [3, -1, 2, 0]ys = [1, 2, -2, 5]k = 2
Output
[[-1, 2], [2, -2]]
Explanation
The squared distances are 10, 5, 8 and 25. The two smallest belong to (-1, 2) with 5 and (2, -2) with 8, in that order.
challenge icon

Follow-up

The points now arrive one at a time, and after each one you must report the k closest so far. How much memory do you need?

Reset code
def kClosest(xs, ys, k):
    # Write code here

Test #1

Test #2

Test #3

Arguments

xs = [3, -1, 2, 0]
ys = [1, 2, -2, 5]
k = 2

Expected Output

[[-1, 2], [2, -2]]