KatInterview

K Nearest Points to Origin

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapdistanceselection

Last updated

Tests heap-based selection and distance computation to efficiently find the k points closest to the origin in 2D space.

You are given a list of n points in 2D space, where each point is represented as [x, y], and a positive integer k where 1 ≤ k ≤ n.

Find the k points that are nearest to the origin (0, 0) measured by Euclidean distance. You may return the points in any order.

When comparing distances, you may use squared Euclidean distance (avoiding the square root) since it preserves the same ordering.

If two points have the same distance from the origin, either may be included in the result.

Constraints

  • 1 ≤ k ≤ points.length ≤ 10⁴
  • Each point [x, y] has integer coordinates where -10⁴ ≤ x, y ≤ 10⁴
  • The origin (0, 0) may appear in the input
  • Return the k nearest points in any order

Examples

Example 1

Input: k_nearest_points([[1, 3], [-2, 2]], 1)

Output: [[-2, 2]]

Example 2

Input: k_nearest_points([[3, 3], [5, -1], [-2, 4]], 2)

Output: [[-2, 4], [3, 3]]

Example 3

Input: k_nearest_points([[0, 0], [1, 1], [-1, -1], [2, 0]], 3)

Output: [[-1, -1], [0, 0], [1, 1]]

Hints

Hint 1

Compare squared distances (x² + y²) instead of taking square roots—it's faster and preserves ordering.

Hint 2

A simple solution sorts all n points by distance, but can you do better when k is much smaller than n?

Hint 3

Maintain a max-heap of size k containing the closest points seen so far. When a closer point arrives and the heap is full, evict the farthest.