Python coding

The k points nearest the origin

Given points, a list of [x, y] pairs with integer coordinates, and an integer k, return the k points nearest the origin (0, 0) by straight-line distance, in any order. A point that appears twice counts twice. k is between 0 and the number of points, and the tests never tie two different points for the last place, so the answer is unique.

Aim for O(n log k): don't sort every point when k is small.

  • nearest_points([[1,3],[-2,2],[5,-1]], 1) → [[-2,2]]
  • nearest_points([[3,3],[5,-1],[-2,4],[0,1]], 2) → [[0,1],[3,3]]
  • nearest_points([[2,0],[0,-2],[4,4]], 2) → [[2,0],[0,-2]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

You never need all the points sorted, only the k best so far. Compare squared distances, x*x + y*y: no square root needed.

Hint 2

Keep a heap of at most k points whose root is the farthest of them. heapq is a min-heap, so push the negated distance.

Hint 3

When the heap grows past k, pop once: that removes the farthest candidate. A min-heap on the plain distance would throw away the nearest instead.

Solution and why it works
pythonO(n log k) · O(k)
import heapq


def nearest_points(points: list[list[int]], k: int) -> list[list[int]]:
    heap = []                                # max-heap by distance: the key is negated
    for x, y in points:
        heapq.heappush(heap, (-(x * x + y * y), x, y))
        if len(heap) > k:
            heapq.heappop(heap)              # evict the farthest of the k + 1
    return [[x, y] for _, x, y in heap]

The heap holds the k nearest points seen so far, with the farthest of them at the root, so each new point costs O(log k): push, and pop if the size passes k. heapq only offers a min-heap, so the key is the negated squared distance. The trap is the heap's direction: a min-heap on the plain distance, capped at k, evicts the nearest point every time and keeps the k farthest. Squared distances keep everything in integers.