Heap
K Closest Points to Origin
DESCRIPTION (inspired by Leetcode.com)
Given a list of points in the form [[x1, y1], [x2, y2], ... [xn, yn]]
and an integer k, find the k closest points to the origin (0, 0) on the 2D plane.
The distance between two points (x, y) and (a, b) is calculated using the formula:
√(x1 - a2)2 + (y1 - b2)2
Return the k closest points in any order.
Example 1:
Inputs:
points = [[3,4],[2,2],[1,1],[0,0],[5,5]] k = 3
Output:
[[2,2],[1,1],[0,0]]
Also valid:
[[2,2],[0,0],[1,1]] [[1,1],[0,0],[2,2]] [[1,1],[2,2],[0,0]] ... [[0,0],[1,1],[2,2]]
Explanation
Approach 1: Sorting
Approach 2: Max Heap
def k_closest(points, k):heap = []for i in range(len(points)):x, y = points[i]distance = x * x + y * yif len(heap) < k:heapq.heappush(heap, (-distance, i))elif distance < -heap[0][0]:heapq.heappushpop(heap, (-distance, i))return [points[p[1]] for p in heap]
initialize heap
0 / 6
def k_closest(points, k):heap = []for i in range(len(points)):x, y = points[i]distance = x * x + y * yif len(heap) < k:heapq.heappush(heap, (-distance, i))elif distance < -heap[0][0]:heapq.heappushpop(heap, (-distance, i))return [points[p[1]] for p in heap]
push to heap
0 / 2
def k_closest(points, k):heap = []for i in range(len(points)):x, y = points[i]distance = x * x + y * yif len(heap) < k:heapq.heappush(heap, (-distance, i))elif distance < -heap[0][0]:heapq.heappushpop(heap, (-distance, i))return [points[p[1]] for p in heap]
distance = 50
0 / 1
Solution
def k_closest(points, k):heap = []for i in range(len(points)):x, y = points[i]distance = x * x + y * yif len(heap) < k:heapq.heappush(heap, (-distance, i))elif distance < -heap[0][0]:heapq.heappushpop(heap, (-distance, i))return [points[p[1]] for p in heap]
k closest points to origin
0 / 11
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n log k) where n is the number of points in the array and k is the input parameter. We iterate over all points, and in the worst case, we both push and pop each point from the heap, which takes O(log k) time per point.
Space Complexity: O(k) where k is the input parameter. The space is used by the heap to store the k closest points to the origin.
Mark as read
Unlock Premium Coding Content
On This Page
Your account is free and you can post anonymously if you choose.