![]() |
VOOZH | about |
Given a set of points in the two-dimensional plane, your task is to find the minimum Euclidean distance between two distinct points.
The Euclidean distance of points (x1,y1) and (x2,y2) is sqrt( (x1-x2)2 + (y1-y2)2 )
Example:
Input: points = {{2, 1} ,{4, 4} ,{1, 2} ,{6, 3}};
Output: 2Input: points = {{2, 12} ,{1, 4} ,{3, 2} ,{1, 3}}
Output: 1
Approach:
We can apply sweep-line Algorithm to solve the above problems. We sort the points based on their x-coordinate and we keep a set of the points in the region x - d, x, sorted by y coordinate. Here d is the smallest distance so far (we can do that with the two-pointers technique). Now, for each new point x, y, we query the whole range y - d, y + d in this set and possibly update our answer.
Due to the proof of the Divide and Conquer algorithm, at each time the queried range should be of size O(1) on average, so total complexity would be O(nlog(n)).
Step-by-step algorithm:
Implementation:
2
Time Complexity: O(n log n), Sorting the points will be O(nlog(n)) and each time the queried range should be of size O(1) on average which can be proved by Divide and Conquer.
Auxiliary Space: O(n), for taking set points.