15% off all plans & roadmaps Use code

See plans

K Closest Points to Origin

Updated

TL;DR: Return the k points with the smallest distance to (0, 0). Compare squared distances and keep a max-heap of size k, so each point costs O(log k) and the heap holds only the best k seen so far.

Problem

You get an array points where points[i] = [xi, yi] is a point on the X-Y plane, and an integer k. Return the k points closest to the origin (0, 0).

Distance is the Euclidean distance, sqrt(x^2 + y^2) for a point measured from the origin. You may return the answer in any order. The answer is guaranteed to be unique, apart from its order.

Example 1

Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation: The distance from (1, 3) to the origin is sqrt(10). The distance from (-2, 2) is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer. We want only k = 1 point, so the answer is [[-2,2]].

Example 2

Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Explanation: The answer [[-2,4],[3,3]] would also be accepted.

Constraints

  • 1 <= k <= points.length <= 10^4
  • -10^4 <= xi, yi <= 10^4

Constraints that matter

  • points.length up to 10^4 means even an O(n^2) scan is only about 10^8 steps at worst, but O(n log n) or better is the target an interviewer expects.
  • Coordinates up to 10^4 in magnitude give a squared distance of at most 2 * 10^8. That fits in a 32-bit int, so there is no overflow and no need for floating point.
  • 1 <= k <= points.length means there is always a valid answer and k is never zero, so the heap never needs an empty-case guard.
  • The answer is guaranteed unique up to order, so ties at the k-th boundary never occur and you do not need a tie-break rule.
  • Any output order is accepted, which is why a heap, whose internal order is partial, is a legal way to build the result.

View on LeetCode

Hints

Hint 1

This is a top-k selection problem.

Hint 2

Pick the closest unused point, mark it used, and repeat k times.

Solution

Intuition

This is a top-k selection problem. You do not need the points fully sorted. You need to know which k of them have the smallest distance, and the order inside that group does not matter.

Picture a shelf that holds only k jars, with the heaviest jar always on top. When a new jar makes k+1, knock the heaviest one off, so the shelf is the heap and jar weight is squared distance.

First, drop the square root. The function sqrt is increasing on non-negative numbers, so xx + yy orders points exactly as the true distance does. Integer comparison is faster and has no rounding error.

Next, ask what you must remember while scanning. Only the best k points so far. A new point can replace only the farthest of those k, so you need fast access to the maximum of a small group, with fast removal and insertion. That is a max-heap capped at size k.

The heap root is the worst point among the current best k. If a new point beats it, the root leaves and the new point enters. If not, the new point cannot be in the answer, because k points already beat it. Every discarded point has at least k better points, so nothing in the final heap is ever wrongly dropped.

Watch the pattern animation

Worked example

Input: points = [[1, 3], [-2, 2]], k = 1
Output: [[-2, 2]]
Explanation: The squared distances are 1*1 + 3*3 = 10 for [1, 3] and 4 + 4 = 8 for [-2, 2]. Only one point may be returned, and 8 is smaller than 10, so the answer is [[-2, 2]].

Approach 1: Brute force: scan for the minimum k times

Pick the closest unused point, mark it used, and repeat k times. Each pick is a full linear scan over all n points. This is the plain translation of "find the closest point, then the next closest, and so on".

It needs no clever structure and it is correct for every input. The cost is k full scans, which grows quickly as k approaches n.

Steps

  1. Create a used array of n flags, all false, and an empty result list.
  2. Repeat k times: set best to none.
  3. Scan every point that is not used and compare its squared distance xx + yy with the current best.
  4. Keep the index of the smallest squared distance.
  5. Mark that index used and append its point to the result.
  6. After k rounds, return the result.

Dry run

Input: points = [[1,3],[-2,2]], k = 1. Squared distances are 10 and 8.

  • Round 1: nothing is used. Scan index 0 (distance 10), best = 0. Scan index 1 (distance 8), 8 < 10, so best = 1.
  • Mark index 1 used and append [-2, 2].
  • k rounds are done, so the result is [[-2, 2]], which matches the expected output.

Complexity

TimeO(n * k)
SpaceO(n)

Here n is the number of points. Each of the k rounds scans all n points once with O(1) work per point, so the total is n * k. In the worst case k equals n, which gives O(n^2), about 10^8 steps at n = 10^4. The used array holds n booleans, which is O(n) extra space besides the output.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        n = len(points)
        used = [False] * n
        result = []
        for _ in range(k):
            best = -1
            best_dist = 0
            for i in range(n):
                if used[i]:
                    continue
                d = points[i][0] * points[i][0] + points[i][1] * points[i][1]
                if best == -1 or d < best_dist:
                    best = i
                    best_dist = d
            used[best] = True
            result.append(points[best])
        return result

Approach 2: Sort by squared distance

What's slow: the brute force rescans all n points for every one of the k picks, so the same distances are compared again and again. When k is large, the work grows toward n^2.

The insight that fixes it: order all points once. A single sort by squared distance puts the k closest points in the first k slots, and a library sort needs only O(n log n) comparisons.

Steps

  1. Define the key of a point as xx + yy. Skip the square root.
  2. Sort the whole points array by this key in ascending order.
  3. Take the first k points of the sorted array.
  4. Return them.

Dry run

Input: points = [[1,3],[-2,2]], k = 1.

  • Keys: [1, 3] has key 10 and [-2, 2] has key 8.
  • Sorted ascending: [[-2, 2], [1, 3]].
  • Take the first k = 1 entries: [[-2, 2]], which matches the expected output.

Complexity

TimeO(n log n)
SpaceO(1) to O(n)

Here n is the number of points. A comparison sort does O(n log n) comparisons, each in O(1) because the key is two multiplications and an add. The extra space depends on the language: in-place sorts such as Java's and Go's use little beyond the stack, while Python's sorted copies the list, which is O(n). The sort also touches points that are not in the answer, so it does more work than necessary when k is small.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        ordered = sorted(points, key=lambda p: p[0] * p[0] + p[1] * p[1])
        return ordered[:k]
Top K Elements (Selection/Frequency) pattern infographic for K Closest Points to Origin

Solution pattern

Top K Elements (Selection/Frequency)

Part of Heap (Priority Queue) Patterns

Approach 3: Max-heap of size kOptimalTop K Elements (Selection/Frequency)

What's slow: sorting orders all n points, including the n - k that will never be returned. Sorting also needs the whole input in memory, and its cost does not shrink when k is small.

The insight that fixes it: keep only the best k points seen so far in a max-heap keyed by squared distance. The root is the farthest of the k.

For each new point, push it. If the heap now holds k + 1 points, pop the root. The popped point is the farthest of the k + 1, so it cannot be in the answer. Each push and pop costs O(log k) instead of a full sort.

Steps

  1. Create an empty max-heap ordered by squared distance, so the farthest point sits at the root.
  2. Walk through the points one at a time.
  3. Push the current point with its squared distance.
  4. If the heap size is now greater than k, pop the root, which removes the farthest point.
  5. After the last point, the heap holds exactly the k closest points.
  6. Copy the heap contents into the result in any order and return it.

Dry run

Input: points = [[1,3],[-2,2]], k = 1. Squared distances are 10 and 8. The heap stores (distance, point) with the largest distance at the root.

StepPointSquared distanceActionHeap afterSize vs k
1[1, 3]10push{(10, [1,3])}1 <= 1, keep
2[-2, 2]8push{(10, [1,3]), (8, [-2,2])}2 > 1, pop
2bpop root (10){(8, [-2,2])}1

After the last point the heap holds one entry, so the result is [[-2, 2]]. This matches the expected output.

Complexity

TimeO(n log k)
SpaceO(k)

Here n is the number of points. The loop runs n times, and each iteration does one push and at most one pop on a heap that never holds more than k + 1 entries. Each heap operation costs O(log(k + 1)), so the total is O(n log k).

The heap stores at most k + 1 entries, so the extra space is O(k) besides the output. When k is close to n, this is no better than sorting, but it never loses by more than a constant factor.

PythonTested in our runner

import heapq
from typing import List, Optional

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        # heapq is a min-heap, so store the negated distance to get a max-heap.
        # The index breaks ties so lists are never compared.
        heap = []
        for i, (x, y) in enumerate(points):
            heapq.heappush(heap, (-(x * x + y * y), i))
            if len(heap) > k:
                heapq.heappop(heap)  # removes the farthest point
        return [points[i] for _, i in heap]

Common mistakes

  • Calling Math.sqrt or ** 0.5 on every point. It adds cost and floating-point noise for no benefit. Compare x*x + y*y directly.
  • Using a min-heap of size k. Popping then removes the closest point, so you keep the k farthest. Store negated distances in Python, or reverse the comparator in Java, so the root is the largest distance.
  • Pushing (dist, [x, y]) into a Python heap with no tie-breaker. Equal distances make Python compare the lists, which works but wastes time and hides intent. Push (-dist, index) instead.
  • Popping before pushing, or popping when len(heap) == k. With the check len(heap) > k after the push, the heap always keeps the k best. Pop only when the size exceeds k.
  • Sorting by a[0] - b[0] or by x + y. The key must be x*x + y*y. Using the sum of coordinates treats (3, -3) as distance 0, which is wrong.
  • Returning points[:k] from the sort version without sorting first, or returning heap entries that still hold the distance. The result must contain only the [x, y] pairs.

Edge cases

  • points = [[0,0]], k = 1: a single point at the origin, so return [[0,0]].
  • k == points.length: every point is returned. The heap never pops, and sorting returns the full array.
  • Negative coordinates such as [-2, 2] and [2, -2] are at the same distance. Squaring removes the sign, and the uniqueness guarantee means such ties never straddle the k-th boundary.
  • Points with large coordinates, such as [10000, 10000]: the squared distance is 2 * 10^8, which fits in a 32-bit int in Java, C++ and C#.
  • Duplicate points, for example [[1,1],[1,1],[5,5]] with k = 2: both copies are kept, giving [[1,1],[1,1]]. Index tie-breakers keep both entries.
  • k = 1 on a large input: the heap holds one entry, so each step is O(1) work and the total is O(n).

Follow-ups interviewers ask

Can you do better than O(n log k) on average?
Yes. Use quickselect on squared distance. Pick a pivot, partition the array around it, and recurse into only the side that contains the k-th boundary. The expected time is O(n). The worst case is O(n^2) with bad pivots, which a random pivot makes very unlikely. It works in place, so extra space is O(1) besides recursion, but it reorders the input.
What if the points arrive as a stream or do not fit in memory?
Use the max-heap of size k. You process one point at a time and keep only k entries, so memory is O(k) regardless of how many points arrive. At any moment the heap holds the k closest points seen so far. Sorting and quickselect both need all points in memory, so they do not apply.
What changes when k is very close to n?
Think of it as removing the n - k farthest points instead. A min-heap of size n - k keyed by distance would hold the points to discard, or you can sort once. When k is near n, the log k factor is close to log n, so the heap has no advantage over a plain sort and the simpler sort is a fine choice.

K Closest Points to Origin FAQ

What is the time complexity of K Closest Points to Origin?

The max-heap solution runs in O(n log k) time and O(k) extra space, where n is the number of points. Sorting is O(n log n). Quickselect is O(n) on average. Repeatedly scanning for the minimum is O(n * k).

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

You want to keep the smallest distances, so the item you must be able to evict quickly is the largest one. A max-heap exposes the largest distance at the root in O(1) and removes it in O(log k). A min-heap would expose the closest point, which is the one you want to keep.

Do I need to take the square root of the distance?

No. Square root is increasing for non-negative numbers, so squared distances sort the points in exactly the same order. Skipping it saves time and avoids floating-point rounding.

Can K Closest Points to Origin be solved in O(1) extra space?

Yes, with caveats. An in-place sort or quickselect uses O(1) extra space, apart from the stack, but it modifies the input array. The max-heap approach needs O(k) space, and keeping the input untouched while using O(1) space is not possible with these methods.

How do I write K Closest Points to Origin in Python with a heap?

Use heapq with negated squared distance: push (-(x*x + y*y), i) and pop when len(heap) > k. The heap then holds the k closest. In Java use a PriorityQueue with a comparator that puts the larger distance first.

Does the order of the returned points matter?

No. The problem accepts any order. A heap returns points in an arbitrary internal order, and the sort version returns them closest first. Both are accepted.

Asked at

See which companies ask this — Pro

Practise it