InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Heap & Priority Queue

K Closest Points to Origin

medium Original ↗ 00:00

Problem

Given a list of points on the plane, points[i] = [x_i, y_i], and an integer k, return the k points closest to the origin (0, 0) by Euclidean distance sqrt(x² + y²).

The answer may be returned in any order. The answer is guaranteed to be unique (no distance ties straddle the k-th place).

Examples

  • points = [[1, 3], [-2, 2]], k = 1[[-2, 2]] — distances are √10 ≈ 3.16 and √8 ≈ 2.83, so [-2, 2] is closer.
  • points = [[3, 3], [5, -1], [-2, 4]], k = 2[[3, 3], [-2, 4]] (any order) — squared distances 18, 26, 20; the two smallest are 18 and 20.
  • points = [[0, 1], [1, 0]], k = 2[[0, 1], [1, 0]] — asking for all points returns all points.

Constraints

  • 1 <= k <= len(points) <= 10^4
  • -10^4 <= x_i, y_i <= 10^4

Think about it first

Hint 1 You only need the *ordering* of distances, never the distances themselves — comparing `x² + y²` gives the same order as comparing `sqrt(x² + y²)`, with no floats.
Hint 2 Sorting all n points works in O(n log n), but you're only asked for k of them. When streaming through the points, what fixed-size structure lets you keep "the k best so far" and evict the current worst in O(log k)?
Hint 3 Max-heap of size k keyed on squared distance (negate for Python): push each point, pop whenever size exceeds k, for O(n log k). For average O(n), use quickselect: partition the array around a pivot distance until the split lands exactly at k.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug