Problem 973

Abstract / Summary

Given a set of points and a number k return the k points closest to the origin sorted by distance.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0973.py

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        minheap = [ ( x*x + y*y, x, y ) for x, y in points ]
        heapify(minheap) # tuples are sorted by first element (= squared distance)

        for _ in range(k):
            d2, x, y = heappop(minheap)
            yield (x, y)
8 lines | 337 bytes | submitted September 28, 2023 | GitHub   14% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Divide And Conquer
  • Geometry
  • Heap (Priority Queue)
  • Math
  • Quickselect
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class with a single method that returns the k points closest to the origin from a list of 2-dimensional integer coordinates. The algorithm relies on a binary min-heap to keep the points ordered by their squared Euclidean distance, which allows efficient extraction of the smallest distances. The method is written as a generator, yielding each selected point one at a time.

Key Steps

Construction of the heap

The first significant operation creates a list of tuples, each containing the squared distance together with the original coordinates. The comprehension iterates over the input list and computes the distance without invoking a square-root function.

minheap = [ ( x*x + y*y, x, y ) for x, y in points ]

Heapification

The list of tuples is transformed into a valid binary min-heap in linear time. Because the tuple’s first element is the squared distance, the heap property automatically orders the entries by proximity to the origin.

heapify(minheap)   # tuples are sorted by first element (= squared distance)

Extraction of the k closest points

A loop runs exactly k times. In each iteration the smallest element is removed from the heap, unpacked into its components, and yielded as a coordinate pair.

for _ in range(k):
    d2, x, y = heappop(minheap)
    yield (x, y)

Edge Cases Handled

When the input list points is empty, the comprehension produces an empty minheap. The subsequent heapify call on an empty list is a no-op, and the for loop will not execute because range(k) still iterates, but the first heappop would raise an exception. The design therefore expects that k is zero or that the caller ensures k does not exceed the number of available points. If k is zero, the loop body is never entered and the generator produces no output, which correctly represents “no closest points”.

The distance calculation uses integer arithmetic (x*x + y*y). This avoids floating-point rounding issues and works correctly for negative coordinates because squaring eliminates sign. The algorithm also tolerates duplicate points; each occurrence is treated as a separate entry in the heap and will be yielded according to its position in the ordering.

Performance Optimizations

The code leverages several implicit optimizations:

  • Avoidance of square roots - By storing the squared distance, the algorithm eliminates the costly sqrt operation while preserving the ordering needed for comparison.
  • Tuple ordering - Python’s heap implementation compares tuples element-wise, so placing the distance first ensures that the heap is ordered solely by distance without extra comparator logic.
  • Linear-time heap construction - Calling heapify on the entire list builds the heap in O(n) time, which is faster than inserting each element individually.
  • Generator pattern - Yielding points one at a time allows the caller to consume results lazily, potentially reducing memory pressure when only a subset of the output is needed.

Overall, the method combines concise Python constructs with the efficiency of the built-in heap module to deliver a solution that scales well for large input sizes while keeping the code compact and readable.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a bunch of colorful stickers scattered all over your bedroom floor, and you want to find the ones that are closest to where you are standing. This code works just like a magic helper that finds those nearby things for you.

First, the code looks at every single sticker and calculates how far away each one is from the center of the room. It uses a little bit of math to turn those spots on the floor into special numbers. After it has all those numbers, it puts them into a special pile called a heap, which is sort of like a magic toy box that always keeps the smallest number right at the very top.

Once everything is tucked away in that pile, the code takes the item from the very top because that represents the sticker closest to you. It repeats this process over and over again until it has picked out exactly as many stickers as you asked for. Each time it grabs one, it sets it aside so you can see which ones are your nearest neighbors.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.70 | σ = 1.63

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python TS Go Rust
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
everthis JS
fartem Ruby
FelixFan1122 Java
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
luangong TS
MacJim C++
qiyuangong Java
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
everthis JavaScript
fartem Ruby
FelixFan1122 Java
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
luangong TypeScript
MacJim C++
qiyuangong Java
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
42 links | 28 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

32 solutions   September 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality