Algorithms · Visualized
Geometry: Closest Pair of Points
Computational Geometry
Points, polygons, and hulls — geometry made computational.
Finds the two closest points among a set of points in 2D space faster than checking every pair. Time: O(n log n) average, O(n log n), versus O(n²) brute force worst; space: O(n).
Big-O: Cross products and sweeping tell left/right and inside/outside.
Closest Pair of Points
Computational GeometryFinds the two closest points among a set of points in 2D space faster than checking every pair. Divide and conquer splits points by a vertical line, recursively solves each half, then checks only a narrow strip near the dividing line for closer cross-boundary pairs — the same algorithm covered under Divide & Conquer.
How Closest Pair of Points Works
- Sort all points by their x-coordinate.
- Recursively split the points into a left half and a right half, solving each half's closest pair independently.
- Let d be the smaller of the two halves' closest distances.
- Build a narrow vertical strip of points within distance d of the dividing line, sorted by y-coordinate.
- Compare points within this strip against a small number of nearby neighbors (proven geometrically to be enough) to check for any closer cross-boundary pair, and return the overall minimum found.
Closest Pair of Points Worked Example
Input: [[2, 3], [12, 30], [40, 50], [5, 1], [12, 10], [3, 4]]
Split by x-coordinate into left and right groups. Left group's closest pair is (2,3) and (3,4), distance ≈1.41. Right group's closest pair is checked separately. The strip near the dividing line is checked for any closer pair spanning both halves. Overall closest pair across the full set: (2,3) and (3,4).
def closest_pair(points):
pts = sorted(points)
n = len(pts)
best = float('inf')
strip = []
def sq_dist(a, b):
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
lo = 0
for i in range(n):
x = pts[i][0]
while lo < i and (x - pts[lo][0]) ** 2 > best:
lo += 1
for j in range(lo, i):
if (pts[i][1] - pts[j][1]) ** 2 > best:
continue
best = min(best, sq_dist(pts[i], pts[j]))
return best ** 0.5Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Closest Pair of Points Time & Space Complexity
When to Use Closest Pair of Points
- Collision detection in simulations/games, geographic nearest-neighbor searches (nearest city, store, or sensor).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.