#973
K Closest Points to Origin
MediumArrayMathDivide and ConquerGeometrySortingHeap (Priority Queue)Quickselect
Approaches
💡
Intuition
Time Space
The brute force approach calculates the distance of each point from the origin and sorts them to find the k closest points. It’s straightforward but inefficient for large datasets.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the Euclidean distance for each point from the origin (0, 0).
- 2Step 2: Store the distances along with their corresponding points.
- 3Step 3: Sort the list of points based on their distances.
- 4Step 4: Return the first k points from the sorted list.
solution.py7 lines
1# Full working Python code
2points = [[1,3],[-2,2]]
3k = 1
4import math
5points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
6result = points[:k]
7print(result)Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.