K Closest Points to Origin
Here is a simple Python solution for this problem. We’ll use the builtin heapq
module in Python, which allows us to create a max heap. The idea is to build a max heap of k elements and then for the remaining elements in the list, if they are closer than the farthest (i.e., max) element in the heap, we remove the max element and add the new one.
Here is the Python code:


In this code, we start by creating an empty heap. Then we iterate over the given points. For each point, we calculate its distance from the origin (0,0), negating the value because Python’s heapq
implements a minheap and we want a maxheap. If our heap has less than k elements, we add the new point. Otherwise, we compare the distance of the current point with the largest distance in our heap. If the current point is closer, we remove the farthest point from the heap and add the current point. Finally, we return a list of the k closest points, discarding the distance information.