Skills101
← All coding problems

K Closest Points to Origin

mediumHeap / Priority Queue+20 XPTime limit 2s

Given n points on a plane, print the k points closest to the origin (0, 0) (Euclidean distance).

Input:

  • line 1: n k
  • next n lines: x y

Output: k lines x y, ordered by distance (closest first). Break ties by smaller x, then smaller y. (Points may repeat; print repeats separately.)

Constraints: 1 ≤ k ≤ n ≤ 5·10⁴, −10⁴ ≤ x, y ≤ 10⁴.

Think about it: compare squared distances x² + y² — no square roots, no floating-point errors (they fit in 32-bit ints). A max-heap of size k keeps the best k seen so far in O(n log k).

Sample input 1

2 1
1 3
-2 2

Sample output 1

-2 2

Sample input 2

3 2
3 3
5 -1
-2 4

Sample output 2

3 3
-2 4

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.