Learn DSA
Depth-First Search
Greedy Algorithms
K Closest Points to Origin
DESCRIPTION (credit 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:
Output:
Also valid:
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
"Write a function that takes a list of points represented as `points` and an integer `k`, and returns the `k` closest points to the origin (0, 0). The distance between two points on a plane is calculated using the Euclidean distance formula."
Run your code to see results here
Have suggestions or found something wrong?
Explanation
Approach 1: Sorting
Approach 2: Min Heap
import heapqdef 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
import heapqdef 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
import heapqdef 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
import heapqdef 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
Complexity Analysis
Login to track your progress
Your account is free and you can post anonymously if you choose.