Algorithms · Visualized
Closest Pair
Divide & Conquer
Break a problem into independent subproblems, solve each, and combine the answers.
Finds the two closest points among a set of points in a plane faster than the O(n²) brute force. Time: O(n log n) average, O(n log n), versus O(n²) brute force worst; space: O(n) — auxiliary arrays for sorting/strip.
Big-O: Classic D&C recursions: Merge Sort, Quick Sort, Maximum Subarray, Fast Power.
Closest Pair of Points
Divide & ConquerFinds the two closest points among a set of points in a plane faster than the O(n²) brute force. Divide and conquer splits the points by a vertical line into left and right halves, recursively finds the closest pair in each half, then checks a narrow 'strip' near the dividing line for any closer cross-boundary pair.
How Closest Pair Works
- Sort points by x-coordinate, then split them into a left half and a right half.
- Recursively find the closest pair distance within the left half.
- Recursively find the closest pair distance within the right half.
- Let 'd' be the smaller of those two distances; build a narrow strip of points within distance 'd' of the dividing line.
- Check points within that strip (sorted by y-coordinate) against each other — thanks to geometry, each point only needs to be compared against a handful of nearby points, not all of them — and return the overall minimum distance found.
Closest Pair Worked Example
Input: [[2, 3], [12, 30], [40, 50], [5, 1], [12, 10], [3, 4]]
Sort by x, split into left and right groups. Left group finds (2,3) and (3,4) as its closest pair, distance ≈1.41. Right group finds its own closest pair. Compare against the strip near the dividing x-value for any closer cross pair. The overall closest pair across the whole set turns out to be (2,3) and (3,4).
import math
def closest_pair(points):
best = float('inf')
n = len(points)
for i in range(n):
for j in range(i + 1, n):
d = math.dist(points[i], points[j])
if d < best:
best = d
return bestBehind 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 Time & Space Complexity
When to Use Closest Pair
- Collision detection in simulations and games (finding nearby objects fast).
- Geographic systems: finding the two closest cities, stores, or sensors from a large set of coordinates.
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.