Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

K Closest Points to Origin

LeetCode #973Medium
Max-heap of size k, keyed by distance

Given an array of points on the plane and a value k, return the k points closest to the origin, measured by Euclidean distance. The answer may be returned in any order.

Asked atAmazonMetaGoogle
step 1 / 17
1,3
-2,2
5,8
0,1
[0][1][2][3]
dist² to origin
·
·
·
·
[0][1][2][3]
Brute force · sort by distance
1given points, k
2compute dist² = x² + y² for each
3sort points by dist²
4return the first k
state
  • k2

line 1Return the k = 2 points NEAREST the origin. "Nearest" = smallest x² + y² — we never need the actual square root, the squared distance orders points the same way.