← Whiteboard questions

K Closest Points to Origin

Find the k points closest to the origin (k delivery stops nearest the depot).

DSA, Medium, Heap / Priority Queue

Which structure or algorithm, and what does it cost.

A courier starts at the depot at (0, 0) on a flat city grid. The list stops holds delivery points, each as [x, y]. Return the k stops with the smallest straight-line distance to the depot, ordered from nearest to farthest. No two stops are the same distance from the depot, so exactly one answer is correct.

Examples

Input stops = [[3, 4], [1, 1], [6, 2], [-2, 0]], k = 2
Output [[1, 1], [-2, 0]]
Why the squared distances are 25, 2, 40 and 4. The two smallest belong to [1, 1] and [-2, 0].
Input stops = [[0, 5]], k = 1
Output [[0, 5]]
Why a single stop is always the closest.
Input stops = [[-1, -1], [2, -3], [0, 1], [5, 5], [-4, 0]], k = 3
Output [[0, 1], [-1, -1], [2, -3]]
Why negative coordinates count by size only. The squared distances are 2, 13, 1, 50 and 16, so the three smallest are 1, 2 and 13.

Constraints

Your answer must contain

Target Aim for O(n log k) time and O(k) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

You do not need the exact distance to compare two stops. Think about a quantity that gives the same order and is easier to compute.

Hint 2 the approach

You only need to remember the k closest stops seen so far, and to know which of them is the farthest.

Hint 3 the key step

Use a max-heap of size k, keyed by squared distance. After each stop, if the heap holds more than k stops, pop the farthest.

Walkthrough

Full walkthrough brute force to best

Brute force

Compute the squared distance of every stop, sort all stops by it, and take the first k. That is O(n log n) time and O(n) memory. It is correct, but it orders all n stops when only k of them matter.

Better method

Quickselect on squared distance puts the k nearest in the first k slots in O(n) average time (O(n^2) worst), then a sort of those k gives the order. It needs the whole list in memory.

Best method

Squared distance, x*x + y*y, orders stops the same way as true distance, so skip the square root. Keep a max-heap of the k closest stops so far, with the farthest of them at the root. For each stop, push it. If the heap now holds more than k stops, pop the root. The root is the farthest kept stop, and it cannot be in the answer, because k nearer stops already exist. After all stops, the heap holds the k closest. Sort those k by distance for the output order. Each stop costs O(log k).

Hand trace

Run on stops [[3, 4], [1, 1], [6, 2], [-2, 0]] with k = 2. [3, 4] has squared distance 25: the heap holds 25. [1, 1] has 2: the heap holds 25 and 2. [6, 2] has 40: push it, the heap has three stops, so pop the farthest, 40. [-2, 0] has 4: push it, then pop the farthest, 25. The heap holds [1, 1] and [-2, 0]. Sorted nearest first, the result is [[1, 1], [-2, 0]].

Code

import heapq
def closest_stops(stops, k):
    heap = []                                   # max-heap through negated squared distances
    for x, y in stops:
        heapq.heappush(heap, (-(x * x + y * y), x, y))
        if len(heap) > k:
            heapq.heappop(heap)                 # drop the farthest kept stop
    heap.sort(reverse=True)                     # nearest first
    return [[x, y] for _, x, y in heap]

Time and memory

O(n log k) time: each of the n stops costs one push and at most one pop on a heap of at most k + 1 stops, and the final sort of k stops adds O(k log k). O(k) memory for the heap.

Common mistakes

  • Using a min-heap of size k. Its root is the nearest stop, so you would drop the wrong ones. The root must be the farthest kept stop.
  • Comparing x + y, or ignoring negative signs. Use x*x + y*y, so a coordinate of -4 counts as 16.
  • Letting the heap grow to n stops. That turns the method into a full sort and loses the O(k) memory.

Related problems

More Heap / Priority Queue problems
K Closest Points to Origin: walkthrough and Python solution