23. K Closest Points to Origin
β GFG solution to the K Closest Points to Origin problem: find k nearest points to origin using efficient selection algorithms like nth_element, sorting, and heaps. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given an integer k and an array of points points[][], where each point is represented as points[i] = [xi, yi] on the X-Y plane, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance, defined as:
distance = sqrt((x2 - x1)Β² + (y2 - y1)Β²)
You can return the k closest points in any order. The driver code will print them in sorted order. Test cases are generated such that there will be a unique answer.
π Examples
Example 1
Input: k = 2, points[] = [[1, 3], [-2, 2], [5, 8], [0, 1]]
Output: [[-2, 2], [0, 1]]
Explanation: The Euclidean distances from the origin are:
Point (1, 3) = sqrt(10)
Point (-2, 2) = sqrt(8)
Point (5, 8) = sqrt(89)
Point (0, 1) = sqrt(1)
The two closest points to the origin are [-2, 2] and [0, 1].Example 2
π Constraints
$1 \le k \le \text{points.size()} \le 10^5$
$-3 \times 10^4 \le x_i, y_i \le 3 \times 10^4$
β
My Approach
The optimal approach uses STL's nth_element algorithm for efficient partial sorting:
nth_element with Lambda Comparator
Calculate Distance:
For each point, the squared Euclidean distance from origin is
xΒ² + yΒ².We avoid computing square roots since comparing squared distances preserves ordering.
Partial Sorting with nth_element:
Use
nth_elementto partition the array such that the k smallest elements (by distance) are placed before position k.The algorithm rearranges elements so that:
Elements before position k are β€ the element at position k
Elements after position k are β₯ the element at position k
No full sorting is required, making it more efficient than complete sort.
Custom Comparator:
Lambda function compares squared distances:
a[0]*a[0]+a[1]*a[1] < b[0]*b[0]+b[1]*b[1]This ensures points are ordered by their proximity to origin.
Extract Result:
Return the first k elements from the rearranged array.
These k elements are guaranteed to be the k closest points.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n) on average, where n is the number of points. The
nth_elementalgorithm uses introselect (a hybrid of quickselect and heapselect), which has linear average-case performance. In the worst case, it can be O(n log n), but this is rare with good pivot selection.Expected Auxiliary Space Complexity: O(1), as
nth_elementperforms in-place partitioning without requiring additional data structures. Only a constant amount of space is used for variables and the lambda function.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Min Heap Approach
π‘ Algorithm Steps:
Push all points with their squared distances into a min heap.
Extract the first k elements from the heap.
These k elements are the closest points to the origin.
Return the result vector containing these k points.
π Complexity Analysis:
Time: β±οΈ O(n log n) - Building heap and extracting k elements
Auxiliary Space: πΎ O(n) - Space for heap storage
β
Why This Approach?
Straightforward heap-based solution
Natural ordering of elements by distance
Good when k is close to n
π 3οΈβ£ Sorting Approach
π‘ Algorithm Steps:
Calculate squared distance for each point.
Sort all points based on their distance from origin.
Take the first k points from the sorted array.
Return these k points as the result.
π Complexity Analysis:
Time: β±οΈ O(n log n) - Sorting operation dominates
Auxiliary Space: πΎ O(1) - In-place sorting
β
Why This Approach?
Clean and simple implementation
Modifies input array in-place
Easy to understand logic
π 4οΈβ£ Quickselect Partition
π‘ Algorithm Steps:
Use quickselect algorithm to partition array around kth element.
Recursively partition until k closest elements are on the left side.
No need to fully sort the array, just partition correctly.
Return the first k elements after partitioning.
π Complexity Analysis:
Time: β±οΈ O(n) average, O(nΒ²) worst - Quickselect partitioning
Auxiliary Space: πΎ O(log n) - Recursion stack space
β
Why This Approach?
Better average time complexity than sorting
Efficient for large datasets with small k
Classic selection algorithm pattern
π 5οΈβ£ Max Heap (Original Approach)
π‘ Algorithm Steps:
Maintain a max heap of size k to store the k closest points.
For each point, calculate its squared distance.
If heap size is less than k, insert the point directly.
Otherwise, compare with the farthest point in heap (top element) and replace if current point is closer.
π Complexity Analysis:
Time: β±οΈ O(n log k) - Each insertion/deletion in heap of size k takes log k time
Auxiliary Space: πΎ O(k) - Heap stores at most k elements
β
Why This Approach?
Space-efficient when k is small compared to n
Optimal for streaming data or when n is very large
Maintains only k elements at any time
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π― nth_element
π’ O(n) avg
π’ O(1)
π Optimal average performance
π§ Modifies input array
πΊ Min Heap
π‘ O(n log n)
π‘ O(n)
π Clear heap semantics
πΎ Extra space for heap
π Sorting
π‘ O(n log n)
π’ O(1)
π― Simple and clean
π Overkill for partial sorting
β‘ Quickselect
π’ O(n) avg
π’ O(log n)
β Good average performance
π§ Complex implementation
ποΈ Max Heap
π’ O(n log k)
π’ O(k)
πΎ Space-efficient for small k
π Slower when k β n
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Optimal performance needed
π₯ nth_element
β β β β β
π Need all sorted
π₯ Sorting
β β β β β
π§ Cannot modify input
π₯ Min Heap
β β β ββ
π― Large n, small k
π Max Heap
β β β β β
π‘ Interview/Competitive
ποΈ Quickselect
β β β β β
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated