πDay 2. K Closest Points to Origin π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an array of points where each point is represented as points[i] = [xi, yi] 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 defined as: $\text{distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$ You may return the k closest points in any order. The driver code will sort them before printing.
π Example Walkthrough:
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 (0,0) are:
Point (1,3) = β10
Point (-2,2) = β8
Point (5,8) = β89
Point (0,1) = β1
The two closest points to the origin are [-2,2] and [0,1].
Example 2:
Input:
k = 1, points = [[2, 4], [-1, -1], [0, 0]]
Output:
[[0, 0]]
Explanation:
The Euclidean distances from the origin (0,0) are:
Point (2,4) = β20
Point (-1,-1) = β2
Point (0,0) = β0
The closest point to the origin is (0,0).
Constraints:
$( 1 \leq k \leq \text{points.size()} \leq 10^5 )$
$( -10^4 \leq x_i, y_i \leq 10^4 )$
π― My Approach:
Partial Sort using nth_element (O(N + K log K) Time, O(1) Space)
nth_element (O(N + K log K) Time, O(1) Space)We need to find the k closest points to the origin based on their Euclidean distance.
Instead of sorting the entire array (which takes O(N log N)), we can use
nth_elementwhich partially sorts the array in O(N + K log K) time.The first k elements in the sorted range will be the k closest points.
Since we donβt need exact sorting,
nth_elementis much more efficient than a full sort.
Algorithm Steps:
Use
nth_elementto place the k closest points at the beginning of the array.Extract the first k points and return them as the result.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(N + K log K), since
nth_elementpartially sorts the array.Expected Auxiliary Space Complexity: O(1), as sorting is done in place without extra memory.
π Solution Code
Code (C++)
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