📖 2 min read
Last updated on

K Closest Points to Origin — Coding Interview Walkthrough


Hero Image for K Closest Points to Origin — Coding Interview Walkthrough

You’re in a coding interview. The interviewer says: “Given a list of points on a 2D plane, return the k closest to the origin.” The obvious answer is sort by distance. But interviewers want the heap solution — O(n log k) instead of O(n log n) — and strong candidates mention Quickselect.


The Problem

Given an array of points where points[i] = [xi, yi], return the k closest to the origin (0, 0). Return the answer in any order.

Example

Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]]

Already comfortable with the solution? Practice it in a mock interview →


What Interviewers Are Actually Testing

SkillWhat Interviewers Observe
Distance comparisonDo you skip sqrt and compare squared distances?
Heap vs. sortDo you know when a max-heap of size k beats full sort?
Python heapqDo you know it’s a min-heap and how to simulate max-heap?

Step 1: The Key Insight

You don’t need sorted order — just the k smallest. A max-heap of size k evicts the farthest candidate each time a closer point arrives.

Max-heap of size k=2 showing squared distances 20 (root) and 18, with the farthest point ready to be evicted. ---

Python Implementation

Max-heap of size k:

import heapq

def kClosest(points: list[list[int]], k: int) -> list[list[int]]:
    max_heap = []
    for x, y in points:
        dist = x**2 + y**2
        heapq.heappush(max_heap, (-dist, x, y))
        if len(max_heap) > k:
            heapq.heappop(max_heap)
    return [[x, y] for _, x, y in max_heap]

Time & Space Complexity

ApproachTimeSpace
SortO(n log n)O(1)
Max-heap of kO(n log k)O(k)
QuickselectO(n) expectedO(1)

Common Interview Mistakes

  1. Using sqrt. Unnecessary — compare x² + y² directly.
  2. Not knowing heapq is min-heap. Negate the key for max-heap behavior.
  3. Proposing Quickselect without O(n²) caveat. Mention randomized pivoting mitigates worst case.

What a Strong Candidate Sounds Like

“Sort by squared distance is O(n log n). When k ≪ n, a max-heap of size k drops to O(n log k). For each point I push onto the heap; if size exceeds k, I pop the farthest. Quickselect gives O(n) expected but I’d go with the heap unless asked to optimize further.”



Practice This in a Mock Interview

Start a mock interview for K Closest Points to Origin on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →