Magicsheet logo

K Closest Points to Origin

Medium
79.5%
Updated 6/1/2025

K Closest Points to Origin

1. What is this problem about?

The K Closest Points to Origin interview question asks you to find the kk points in a 2D plane that are closest to the origin (0,0)(0, 0). Distance is measured using the standard Euclidean formula: x2+y2\sqrt{x^2 + y^2}. Since we are only comparing distances, you can simplify the math by using squared distance x2+y2x^2 + y^2.

2. Why is this asked in interviews?

This is a standard question at companies like Meta, Amazon, and Salesforce. it tests your knowledge of Sorting and Heaps. For large datasets where kk is small, interviewers look for the O(NlogK)O(N \log K) heap approach or the O(N)O(N) Quickselect algorithm. it evaluations your ability to optimize for specific kk values.

3. Algorithmic pattern used

There are three main patterns for this problem:

  1. Sorting (O(NlogN)O(N \log N)): Sort all points by distance and return the first kk. Simple but not optimal for small kk.
  2. Max-Heap (O(NlogK)O(N \log K)): Maintain a Max-Heap of size kk. If a new point is closer than the heap's top (the furthest of the current kk best), replace the top.
  3. Quickselect (O(N)O(N) average): Use the quicksort partitioning logic to find the kthk^{th} smallest distance and return all points to its left.

4. Example explanation

Points: [[1, 3], [-2, 2]], k=1k = 1

  1. Distances squared:
    • (1,3)o12+32=10(1, 3) o 1^2 + 3^2 = 10.
    • (2,2)o(2)2+22=8(-2, 2) o (-2)^2 + 2^2 = 8.
  2. The point (2,2)(-2, 2) is closer. Result: [[-2, 2]].

5. Common mistakes candidates make

  • Slow Math: Calculating the square root unnecessarily. d12<d22d1^2 < d2^2 implies d1<d2d1 < d2.
  • Heap Choice: Using a Min-Heap to store all NN elements (O(NlogN)O(N \log N)) instead of a Max-Heap of size kk (O(NlogK)O(N \log K)).
  • Tie-breaking: Not being consistent with points that have the same distance (though most problems don't require specific tie-breaking).

6. Interview preparation tip

Master Quickselect. It is the most impressive answer for any "Top K" or "Kth smallest" problem because it provides linear time complexity. Be ready to explain why the average time is O(N)O(N) but the worst case is O(N2)O(N^2). This is a core Quickselect interview pattern.

Similar Questions