K Closest Points to Origin
Master this topic with zero to advance depth.
K Closest Points to Origin
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 .
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Visual Representation
points = [[1,3],[-2,2]], k = 1
Distance of [1,3] = sqrt(1^2 + 3^2) = sqrt(10) â 3.16
Distance of [-2,2] = sqrt((-2)^2 + 2^2) = sqrt(8) â 2.83
Closest Point: [-2, 2]Examples
Level I: Sorting (Naive)
Intuition
Calculate the squared distance for every point, then sort all points based on these distances. Return the first k points.
Thought Process
- Use a custom comparator to compare points and based on vs .
- Sort the array using this comparator.
- Return the sub-array of size
k.
Detailed Dry Run
points = [[1,3], [-2,2]], k = 1
- Dist sq: [10, 8]
- Sorted by dist: [[-2,2], [1,3]]
- Take first k=1: [[-2,2]]
Level II: Quickselect (Average Case Optimal)
Intuition
Similar to Kth Largest Element, we can use the Partition logic to find the closest points in average time.
Thought Process
- Define distance function .
- Partition the points based on .
- If pivot index equals , all points to the left are the closest.
- Recurse into the necessary partition.
Detailed Dry Run
points = [[3,3], [5,-1], [-2,4]], k = 2 Distances: [18, 26, 20]
- Partition around pivot 20: [[3,3], [-2,4], [5,-1]]. Pivot 20 is at index 1.
- k=2, so we need to ensure index 1 is part of the result. Return points[0...1].
Level III: Max-Heap (Optimal)
Intuition
Maintain a Max-Heap of size k to store the points with the smallest distances. If we find a point with a smaller distance than the maximum in our heap, we replace the maximum with it.
Thought Process
- Initialize a Max-Heap based on squared Euclidean distance.
- Iterate through all
points. - Push the current point into the heap.
- If heap size >
k, pop the point with the largest distance (the root). - After all points are processed, the heap contains the
kclosest points.
Detailed Dry Run
points = [[3,3],[5,-1],[-2,4]], k = 2
- Point [3,3], Dist 18: Heap [[3,3] (Dist 18)]
- Point [5,-1], Dist 26: Heap [[5,-1] (Dist 26), [3,3] (Dist 18)]
- Point [-2,4], Dist 20: Heap [[5,-1] (Dist 26), [-2,4], [3,3]] -> Pop [5,-1]. Final Heap: [[-2,4], [3,3]]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.