Closest Points to the Origin
Write k_closest(points, k) that returns the k points closest to the origin (0, 0) as a list of (x, y) tuples, nearest first. If two points are equally far, the one with the smaller x comes first, and if still equal, the smaller y. If k is larger than the number of points, return them all.
Understand the problem
Decide how to measure distance, and how to break ties.
To compare distances from the origin, do you need the square root?
- Yes, always
- No:
x*x + y*yorders points the same way and avoids floating point - Only for negative points
The square root is an increasing function, so the order of the squared distances equals the order of the real distances. Skipping it is faster and keeps everything in exact integers.
Which sort key gives "nearest first, then smaller x, then smaller y"?
lambda p: p[0]**2 + p[1]**2lambda p: (p[0]**2 + p[1]**2, p[0], p[1])lambda p: (p[0], p[1])
A tuple key compares its parts in turn. The squared distance first; points with the same distance are then ordered by x and then y. Since p is itself the tuple (x, y), (distance, p) does the same.
Write the solution
Return the list.
def k_closest(points, k):
# Write your code here.
pass
Hint 1: a question to ask yourself
What should the sort key be, so that one sort gives the whole order you need?
Hint 2: the shape of the answer
sorted(points, key=...)[:k], or heapq.nsmallest(k, points, key=...), which does not sort everything.
Reflect
Solution
def k_closest(points, k):
def key(point):
x, y = point
return (x * x + y * y, x, y)
return sorted(points, key=key)[:k]
Another way: heapq.nsmallest
import heapq
def k_closest(points, k):
return heapq.nsmallest(k, points, key=lambda p: (p[0] * p[0] + p[1] * p[1], p[0], p[1]))
What this tests: sort keys with tuples, heapq.nsmallest, slicing, and ties.
Sorting everything versus a heap: sorting costs O(n log n). nsmallest(k, ...) keeps a heap of size k and costs O(n log k), which is better when k is small and n is large (the 10 nearest of a million points).
Skip the square root: monotonic transformations do not change the order, so compare the cheaper quantity. A frequent interview point.
Always say how you break ties. Without it, two correct programs can give different answers.
What an interviewer might ask next: Do it for a stream of points where you can keep only k of them in memory. (A heap of size k with the farthest on top; replace it when a closer point arrives.)
VISIBLE = 3
CASES = [
(([(1, 1), (3, 3), (0, 2)], 2), [(1, 1), (0, 2)], 'two nearest'),
(([(5, 5), (1, 0), (0, 1), (-1, 0)], 3), [(-1, 0), (0, 1), (1, 0)], 'ties broken by x then y'),
(([], 3), [], 'no points'),
(([(2, 2)], 5), [(2, 2)], 'k larger than the number of points'),
(([(3, 4), (0, 5), (-5, 0)], 3), [(-5, 0), (0, 5), (3, 4)], 'three points at distance 5'),
(([(1, 2), (2, 1)], 1), [(1, 2)], 'a tie, smaller x first'),
(([(0, 0), (1, 1)], 0), [], 'k is zero'),
(([(-3, -4), (3, 4), (0, 1)], 2), [(0, 1), (-3, -4)], 'negative coordinates'),
]