Medium: Interview Core · Problem 59 of 82

Closest Points to the Origin

MediumStandard LibraryPython

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?

  1. Yes, always
  2. No: x*x + y*y orders points the same way and avoids floating point
  3. 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"?

  1. lambda p: p[0]**2 + p[1]**2
  2. lambda p: (p[0]**2 + p[1]**2, p[0], p[1])
  3. 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.)