Find the K Closest Points to a Query Location

Quick Overview

Return the k points closest to a two-dimensional query location with deterministic distance and coordinate tie breaks. Avoid square roots and use a size-k max-heap to achieve O(n log k) time and O(k) space when k is small.

Find the K Closest Points to a Query Location

Company: Uber

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

Implement `k_closest_points(points, origin, k)` for two-dimensional integer points. Return the `k` points closest to the query location `origin`. Rank points by squared Euclidean distance, then by `x`, then by `y`; return the selected points in that order. This tie-breaking rule makes the answer deterministic. `k` will not exceed the number of points. Avoid square roots. When `k` is much smaller than the number of points, target `O(n log k)` time and `O(k)` auxiliary space. ```hint Keep only the current winners Maintain a size-`k` max-heap ordered by the same distance and coordinate key used for the final result. ``` ```hint Preserve deterministic ties The heap's notion of the worst retained point must reverse the complete ranking key, not only the distance. ``` ### Discussion Extensions - How could quickselect reduce expected running time when all points are available as one batch? - For millions of moving points, compare a uniform grid, a quadtree, and a hierarchical spatial cell index. - If final ranking uses road-network travel distance, where can straight-line distance still provide a safe candidate filter?

Quick Answer: Return the k points closest to a two-dimensional query location with deterministic distance and coordinate tie breaks. Avoid square roots and use a size-k max-heap to achieve O(n log k) time and O(k) space when k is small.

|Home/Coding & Algorithms/Uber
Uber logo
Uber
Aug 16, 2026, 12:00 AM
mediumSoftware EngineerOnsiteCoding & Algorithms
0
0

Implement k_closest_points(points, origin, k) for two-dimensional integer points.

Return the k points closest to the query location origin. Rank points by squared Euclidean distance, then by x, then by y; return the selected points in that order. This tie-breaking rule makes the answer deterministic. k will not exceed the number of points.

Avoid square roots. When k is much smaller than the number of points, target O(n log k) time and O(k) auxiliary space.

Discussion Extensions

  • How could quickselect reduce expected running time when all points are available as one batch?
  • For millions of moving points, compare a uniform grid, a quadtree, and a hierarchical spatial cell index.
  • If final ranking uses road-network travel distance, where can straight-line distance still provide a safe candidate filter?

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...