Problem · Geometry

K Closest Points to a Query Point

Learn this problem
MediumUber logoUberFULLTIMEONSITE INTERVIEW
See Uber hiring insights

Problem statement

Given distinct planar integer points points, a query point query, and an integer k, return the k points with the smallest squared Euclidean distance from query.

Order the result by increasing squared distance, then increasing x, then increasing y.

Function

kClosestToQuery(points: int[][], query: int[], k: int) → int[][]

Examples

Example 1

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

Both returned points have squared distance 8; lexicographic coordinates break the tie.

Example 2

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

The squared distances are 5, 32, and 5; coordinate order resolves the tie at distance 5.

Constraints

  • points is non-empty and contains distinct coordinate pairs.
  • query contains exactly two signed integers.
  • 1 <= k <= points.length.
  • Every squared distance fits in a signed 64-bit integer.

More Uber problems

drafts saved locally
public int[][] kClosestToQuery(int[][] points, int[] query, int k) {
    // TODO: return the deterministically ordered k closest points.
}
points[[1,3],[-2,2],[2,-2]]
query[0,0]
k2
expected[[-2,2],[2,-2]]
checking account