Skip to content
BytePatterns

Closest Points To Origin

MediumHeaps#max-heap#top-k~30m

Problem

Given points on a plane and a number k, return the k points lying closest to the origin. Distance is the ordinary straight-line distance. Report the chosen points ordered by distance, and when two points are equally far away prefer the one with the smaller first coordinate, then the smaller second one.

Examples

Input:  points = [[3, 3], [5, -1], [-2, 4]], k = 2
Output: [(3, 3), (-2, 4)]
Why:    their squared distances are 18 and 20, while the middle point sits at 26
Input:  points = [[1, 0], [0, 1]], k = 1
Output: [(0, 1)]
Why:    edge case, an exact tie is broken by the smaller first coordinate
Input:  points = [[1, 3], [-2, 2]], k = 1
Output: [(-2, 2)]

Hints

0 / 3

Stuck on the idea rather than the code? K Closest Points covers it.