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)
Difficulty
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
AI Disclaimer
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.
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
sqrtoperation 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
heapifyon 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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Similar Problems
- problem 215: Kth Largest Element in an Array
- problem 347: Top K Frequent Elements
- problem 692: Top K Frequent Words
- problem 1779: Find Nearest Point That Has the Same X or Y Coordinate
- problem 3111: Minimum Rectangles to Cover Points
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 912: Sort an Array
- problem 923: 3Sum With Multiplicity
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
- problem 1366: Rank Teams by Votes
- problem 1419: Minimum Number of Frogs Croaking
- problem 1738: Find Kth Largest XOR Coordinate Value
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 906: Super Palindromes
- problem 992: Subarrays with K Different Integers
- problem 1106: Parsing A Boolean Expression
- problem 1601: Maximum Number of Achievable Transfer Requests
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
Extra
- 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