K Closest Points to Origin
Learn how to solve the 'K Closest Points to Origin' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., sqrt((x1 - x2)^2 + (y1 - y2)^2)).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Write a function kClosest(points: List[List[int]], k: int) -> List[List[int]].
- •1 <= k <= len(points) <= 10^4
- •-10^4 <= xi, yi <= 10^4
Examples
points = [[1,3],[-2,2]], k = 1
[[-2,2]]
The distance from (1, 3) to the origin is sqrt(10). The distance from (-2, 2) to the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
points = [[3,3],[5,-1],[-2,4]], k = 2
[[3,3],[-2,4]]
The closest two points are (3, 3) and (-2, 4). (Order of elements in the output does not matter).
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.