← Back to Algorithms, page 4

algorithms-0062 · Medium fresher

K closest points to the origin: given points on a plane, return the k nearest ones using a heap so the full list never has to be sorted.

Compare squared distances to avoid square roots. Keep a max-heap of size k (store negative distances in Python): push each point, and when the heap is full replace the top if the new point is closer. That is O(n log k) time and O(k) space. Sorting all points is O(n log n), and quickselect gives O(n) average.

Full answer

Problem

Given a list of points [x, y] and an integer k, return the k points closest to (0, 0) by Euclidean distance, in any order.

Example: points [[3, 3], [5, -1], [-2, 4]], k = 2 returns [[3, 3], [-2, 4]] (squared distances 18, 26, 20).

Constraints: 1 <= k <= n <= 10^4; coordinates from -10^4 to 10^4. The answer is unique up to ties.

Brute force

Sort all points by distance and take the first k: O(n log n) time, O(n) space for the sorted copy.

Optimal approach

Maintain a max-heap of the k best points seen so far, keyed by squared distance.

  • If the heap has fewer than k items, push.
  • Otherwise, if the new distance is smaller than the heap's maximum, replace the top (heapreplace).

At the end the heap holds the answer.

Why it works

The heap always holds the k closest points among those processed, with the farthest of them at the top. A new point belongs in the answer exactly when it is closer than that farthest one, and then the farthest one is the point that drops out. Squared distance preserves order because squaring is monotonic for non-negative values.

Complexity

O(n log k) time, O(k) space. Quickselect (partition around a pivot until index k) is O(n) average and O(n^2) worst case, and it rearranges the input.

Code

python
import heapq
import random


def k_closest(points, k):
    """Keep a max-heap of size k keyed by -distance. O(n log k) time, O(k) space."""
    heap = []
    for x, y in points:
        d = x * x + y * y                # squared distance: no sqrt needed to compare
        if len(heap) < k:
            heapq.heappush(heap, (-d, x, y))
        elif -heap[0][0] > d:
            heapq.heapreplace(heap, (-d, x, y))
    return [[x, y] for _, x, y in heap]


def brute(points, k):
    """Sort everything: O(n log n)."""
    return sorted(points, key=lambda p: p[0] ** 2 + p[1] ** 2)[:k]


def dists(pts):
    return sorted(x * x + y * y for x, y in pts)


if __name__ == "__main__":
    assert sorted(k_closest([[1, 3], [-2, 2]], 1)) == [[-2, 2]]
    assert sorted(k_closest([[3, 3], [5, -1], [-2, 4]], 2)) == [[-2, 4], [3, 3]]
    assert k_closest([[0, 0]], 1) == [[0, 0]]
    rng = random.Random(62)
    for _ in range(1000):
        pts = [[rng.randint(-10, 10), rng.randint(-10, 10)] for _ in range(rng.randint(1, 30))]
        k = rng.randint(1, len(pts))
        got = k_closest(pts, k)
        assert len(got) == k and dists(got) == dists(brute(pts, k))   # ties may pick different points
    print("all tests passed")

Save as b62_k_closest.py and run python3 b62_k_closest.py. It prints all tests passed (Python 3.13.5).

Edge cases

k equals n (return all). Ties in distance (any valid set is accepted; tests compare distances). Duplicate points. Points at the origin. Large coordinates: squared values fit easily in Python ints; in 32-bit languages, use 64-bit integers.

Pattern

Bounded heap for top-k: keep the k best in a heap ordered by the worst of them. The same pattern gives kth largest in a stream, top-k frequent words, and nearest neighbours in a streaming feed. When the data fits in memory and order does not matter, quickselect is the alternative.

python
import heapq
import random


def k_closest(points, k):
    """Keep a max-heap of size k keyed by -distance. O(n log k) time, O(k) space."""
    heap = []
    for x, y in points:
        d = x * x + y * y                # squared distance: no sqrt needed to compare
        if len(heap) < k:
            heapq.heappush(heap, (-d, x, y))
        elif -heap[0][0] > d:
            heapq.heapreplace(heap, (-d, x, y))
    return [[x, y] for _, x, y in heap]


def brute(points, k):
    """Sort everything: O(n log n)."""
    return sorted(points, key=lambda p: p[0] ** 2 + p[1] ** 2)[:k]


def dists(pts):
    return sorted(x * x + y * y for x, y in pts)


if __name__ == "__main__":
    assert sorted(k_closest([[1, 3], [-2, 2]], 1)) == [[-2, 2]]
    assert sorted(k_closest([[3, 3], [5, -1], [-2, 4]], 2)) == [[-2, 4], [3, 3]]
    assert k_closest([[0, 0]], 1) == [[0, 0]]
    rng = random.Random(62)
    for _ in range(1000):
        pts = [[rng.randint(-10, 10), rng.randint(-10, 10)] for _ in range(rng.randint(1, 30))]
        k = rng.randint(1, len(pts))
        got = k_closest(pts, k)
        assert len(got) == k and dists(got) == dists(brute(pts, k))   # ties may pick different points
    print("all tests passed")

Size-k max-heap with squared distances, checked against full sorting on random inputs by comparing the multiset of distances.

Complexity

Time: O(n log k). Space: O(k). Quickselect is O(n) average; sorting is O(n log n).

By level

Fresher: Sorts by squared distance as a first answer, then explains the size-k heap and when the top is replaced. States the time complexity of each.

Mid: Implements the bounded heap correctly and compares it with quickselect on time, memory and input mutation. Handles streaming input.

Senior: Discusses spatial indexes such as k-d trees, geohash cells and approximate nearest neighbour indexes for repeated queries. Weighs exactness against latency for large-scale proximity search.

Key points

  • Use squared distance
  • Max-heap of size k holds the current best
  • Replace the top only when the new point is closer
  • O(n log k) beats O(n log n) for small k
  • Quickselect is the O(n) average alternative

Common mistakes

  • Using a min-heap of all n points and popping k (O(n + k log n), fine, but not the bounded version asked)
  • Computing sqrt needlessly
  • Forgetting to negate for a max-heap in Python
  • Assuming a unique answer when ties exist

Follow-ups

  • How would you handle a stream of points where k stays fixed?
  • When is quickselect better than a heap?
  • How would you find k nearest neighbours to an arbitrary query point many times (k-d tree)?

Tips

  • Mention squared distance early
  • State why the heap holds the farthest of the best at the top
  • Offer quickselect as an alternative

Evaluation rubric

  • Correct bounded-heap logic
  • Correct complexity
  • Handles ties
  • Knows the quickselect option