K Closest Points to Origin solution explained

To return the k points closest to the origin, rank points by squared distance, x² + y², which keeps the same order as true distance without a square root. Sorting by that key is O(n log n). A max-heap that never holds more than k points is O(n log k), and quickselect on the distances is O(n) on average.

By Published 7 min read

Restating the task

You receive a list of points on a flat grid, each given as two integers, and a number k no larger than the list's length. Return the k points with the smallest straight-line distance to the origin. The output order does not matter. If two points are equally far and only one of them fits, either choice is accepted unless the interviewer adds a tie rule.

Point sets made up for this page
PointskA valid answerSquared distances
(2, -1), (0, 3), (-1, -1), (4, 0)2(-1, -1), (2, -1)5, 9, 2, 16
(1, 2), (2, 1), (0, 1)2(0, 1) and either (1, 2) or (2, 1)5, 5, 1: a tie for second place
(-3, 4)1(-3, 4)25
(0, 0), (5, 0), (0, -5)3All three0, 25, 25
Point sets made up for this page. Scroll sideways on a small screen.

Questions to ask up front: can coordinates be negative (yes, usually), can the same point appear twice, does the output need to be sorted by distance, and how big can coordinates get. The last one matters in languages with fixed-size integers, because x² + y² can overflow a 32-bit int when coordinates reach the tens of thousands.

What a good answer shows

The problem combines two small insights with a selection technique. Skipping the square root shows you think about what the comparison really needs. Using a max-heap to find the smallest values, which feels backwards at first, shows you understand why the heap's top must be the item you would throw away. Interviewers at the senior end often ask for the quickselect version or for a streaming variant.

Where the conversation can go next

  • Points arrive one at a time and the list never ends. The size-k heap keeps working with O(k) memory; quickselect cannot, because it needs every point at once.
  • Closest to some point other than the origin. Subtract that point's coordinates first. Nothing else changes.
  • Return the result sorted by distance. Sort the k winners afterward, O(k log k).
  • Points in three dimensions, or millions of repeated queries. For many queries against fixed points, a spatial index such as a k-d tree is the usual answer; describe it rather than code it.

Simple version: sort every point

Sort the whole list with squared distance as the key and keep the first k. It is short, clearly correct and O(n log n). Python's sort is stable, so equally distant points keep their input order, which can be handy if the interviewer asks for a deterministic tie rule.

def k_closest_by_sorting(points, k):
    return sorted(points, key=lambda p: p[0] * p[0] + p[1] * p[1])[:k]
Sort by squared distance and slice. O(n log n).

Max-heap of the k best so far

Walk the points once. While the heap holds fewer than k items, add the current point. After that, compare each new point with the farthest point currently kept, which is the heap's top. If the new point is closer, it replaces the top; otherwise ignore it. When the walk ends, the heap holds exactly the k closest points. Python only has a min-heap, so store the negated distance. Storing the point's index alongside it avoids a subtle problem: on equal distances Python would compare the next tuple field, and comparing indices is always safe and cheap.

import heapq


def k_closest(points, k):
    # Max-heap of the k best so far, as (-squared distance, index).
    # The index breaks ties, so two points are never compared directly.
    heap = []
    for i, (x, y) in enumerate(points):
        d = x * x + y * y
        if len(heap) < k:
            heapq.heappush(heap, (-d, i))
        elif d < -heap[0][0]:
            heapq.heapreplace(heap, (-d, i))
    return [points[i] for _, i in heap]
Size-k max-heap through negated distances. O(n log k) time, O(k) space.

Seeing a max-heap used to collect the smallest values is the moment many candidates hesitate. Put it this way: the heap is a waiting list of k places, and the top is the weakest member, the first to be bumped when someone better shows up.

Quickselect in JavaScript

If all points are available and you may reorder a copy, quickselect does better on average. Choose a random pivot point, move every point closer than it to the left, and place the pivot right after them. If the pivot lands at index k - 1, the first k positions are the answer. Otherwise keep working only on the side that contains index k - 1. Expected time is linear. The worst case is quadratic, and this two-way partition hits it when many points share one distance, so mention a three-way partition if the data might look like that.

function kClosest(points, k) {
  const pts = points.slice();
  const dist = (p) => p[0] * p[0] + p[1] * p[1];
  let lo = 0;
  let hi = pts.length - 1;
  while (lo < hi) {
    // A random pivot keeps the expected time linear.
    const pick = lo + Math.floor(Math.random() * (hi - lo + 1));
    [pts[pick], pts[hi]] = [pts[hi], pts[pick]];
    const pivotDist = dist(pts[hi]);
    let store = lo;
    for (let i = lo; i < hi; i++) {
      if (dist(pts[i]) < pivotDist) {
        [pts[i], pts[store]] = [pts[store], pts[i]];
        store++;
      }
    }
    [pts[store], pts[hi]] = [pts[hi], pts[store]];
    if (store === k - 1) break;
    if (store < k - 1) lo = store + 1;
    else hi = store - 1;
  }
  return pts.slice(0, k);
}
Quickselect on squared distance with a random pivot. O(n) average.

JavaScript numbers are doubles, so squared distances stay exact up to about 9 × 10^15, well beyond typical coordinate ranges. In C++ or Java, compute the squares in a 64-bit type.

Comparing the three

n points, k requested
MethodTimeExtra spaceBest for
Sort by squared distanceO(n log n)O(n)Clarity and a stable tie order
Max-heap of size kO(n log k)O(k)Small k, or points that stream in
QuickselectO(n) average, O(n²) worstO(n) for the copyOne batch query, speed on average
n points, k requested. Scroll sideways on a small screen.

Cases to run

  • k equal to the number of points: return them all.
  • The origin itself as one of the points, distance zero.
  • Ties at the cut-off, such as (1, 2) and (2, 1) when only one fits.
  • The same point listed twice; both copies count as separate points.
  • Points that are all the same distance, which is the slow case for two-way quickselect.

Mistakes that cost points

  • Taking square roots and then comparing floats, which adds cost and can mis-order nearly equal distances.
  • Using a min-heap of every point and popping k times, then calling it O(n log k).
  • Pushing raw lists into heapq without an index, which falls back to comparing the lists on ties.
  • Mutating the caller's array during quickselect without saying so.
  • Overflowing 32-bit integers when squaring large coordinates in C++ or Java.

Explaining your choice

Fictional example

How a candidate might frame the heap
Candidate
I'll compare squared distances, since the square root doesn't change the order.
Candidate
I want the k smallest, so I keep a max-heap of size k. The top is the worst point I'm currently keeping. Each new point either beats it and replaces it, or gets skipped.
Interviewer
Why not a min-heap?
Candidate
A min-heap would need every point in it, n log n to build and pop. With the max-heap I only ever compare against the one point I'd evict, so it's n log k and k memory. If points kept arriving, it would still work.

Next problems to try

Kth Largest Element in an Array is the one-dimensional version of this selection and covers the three-way partition. Task Scheduler and Find Median from Data Stream keep heaps alive across many steps. Last Stone Weight is the quickest heap warm-up, and Top K Frequent Elements selects by count instead of distance.

Using Natively to rehearse

If you practice on a judge site in Chrome, the Natively Companion extension lets Natively read the problem straight from the page, and on any screen it can work from a screenshot instead. It drafts an approach and code in its overlay on Mac or Windows, so you can compare its heap or quickselect choice with yours. In spoken mock rounds held over a call, it transcribes you and your practice partner as separate channels. Details on Natively for coding interviews.

Questions people ask

Why use a max-heap for K Closest Points to Origin?

The heap holds the k closest points found so far, and its top is the farthest of them, the one to evict when a closer point arrives. That keeps the heap at size k, for O(n log k) time and O(k) space.

Do you need the square root to compare distances?

No. Squared distance x² + y² sorts points in the same order as true distance, and it avoids floating-point work. Use a 64-bit type for the squares in languages with fixed-size integers.

Can K Closest Points to Origin be solved in O(n)?

On average, yes, with quickselect on squared distances and a random pivot. The worst case is O(n²). The heap is O(n log k) and works on streams, which quickselect cannot.

What if two points are the same distance from the origin?

Unless a tie rule is given, either point is a valid answer. If the interviewer wants a fixed rule, sort or heap on a pair such as (distance, x, y).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP