Closest Pair of Points - Problem

Given an array of points in a 2D plane, find the closest pair of points and return the minimum distance between them.

Each point is represented as [x, y] where x and y are integers.

The distance between two points (x1, y1) and (x2, y2) is calculated using the Euclidean distance formula: √((x2-x1)² + (y2-y1)²)

Your solution must run in O(n log n) time complexity using a divide and conquer approach.

Input & Output

Example 1 — Basic Case
$ Input: points = [[0,2],[1,4],[4,1],[5,3]]
Output: 2.23606797749979
💡 Note: The closest pair is (0,2) and (1,4) with distance √((1-0)² + (4-2)²) = √(1+4) = √5 ≈ 2.236
Example 2 — Minimum Size
$ Input: points = [[1,1],[3,4]]
Output: 3.605551275463989
💡 Note: Only two points: distance = √((3-1)² + (4-1)²) = √(4+9) = √13 ≈ 3.606
Example 3 — Same Distance
$ Input: points = [[0,0],[1,0],[0,1],[1,1]]
Output: 1.0
💡 Note: Multiple pairs have distance 1.0: (0,0)-(1,0), (0,0)-(0,1), (1,0)-(1,1), (0,1)-(1,1)

Constraints

  • 2 ≤ points.length ≤ 104
  • -104 ≤ xi, yi ≤ 104
  • All points are distinct

Visualization

Tap to expand
Closest Pair of Points - Divide & ConquerINPUT: Point ArrayALGORITHM STEPSRESULT(0,2)(1,4)(4,1)(5,3)Points: [[0,2],[1,4],[4,1],[5,3]]1Sort by X-coordinateOrder points left to right2Divide RecursivelySplit plane into left/right halves3Solve Sub-problemsFind closest in each half4Check Boundary StripExamine cross-boundary pairsMinimum Distance2.236Between points (0,2) and (1,4)Distance = √((1-0)² + (4-2)²) = √5Key Insight:Divide and conquer reduces O(n²) comparisons to O(n log n) byrecursively splitting the plane and only checking boundary points that could improve the current best.TutorialsPoint - Closest Pair of Points | Divide & Conquer
Asked in
Google 35 Microsoft 28 Amazon 22 Facebook 18
28.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen