VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-minimum-euclidean-distance/

⇱ CSES Solutions - Minimum Euclidean Distance - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Minimum Euclidean Distance

Last Updated : 23 Jul, 2025

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: 2

Input: 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:

  • Sort the points based on their X coordinates.
  • Initialize a variable to hold the minimum square distance, starting with the maximum possible value.
  • Loop through each point.
    • Calculate a distance threshold based on the current minimum distance found.
    • Create a set to store active points, starting with the first point.
    • Iterate through points already considered, removing those that are too far away i.e. more than d.
      • Find points within the bounding box defined by the distance threshold.
      • Calculate the distance between the current point and points within the bounding box.
      • Update the minimum square distance if a closer point is found.
  • Print the minimum square distance found.

Implementation:


Output
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.

Comment
Article Tags:
Article Tags: