Sub topic 16
Closest Pair of Points in the Plane
This chapter assumes you know merge sort, the recurrence T(n) = 2T(n/2) + O(n), and the crossing-case idea from the maximum subarray chapter. Closest pair uses the same plan: solve the left half, solve the right half, then deal with answers that cross the split.
The Problem
You have n distinct points in the plane, and you want the smallest Euclidean distance between any two of them. If you check every pair, you do n(n-1)/2 distance computations, which is O(n²). Divide and conquer brings this down to O(n log n).
The Three Steps
- Divide. Sort the points by x. Then split them at the median x into a left half and a right half.
- Conquer. Find the closest distance in each half recursively. Call the smaller of the two results d.
- Combine. A closer pair can only cross the dividing line. Both of its points must lie within distance d of that line, so you only need to look inside a vertical strip of width 2d.
Why the Strip Is Cheap
The strip could hold every point, so it is not obvious that it is cheap to scan. The key is a packing argument. Take the strip points sorted by y. For any point p, consider the d × 2d rectangle that starts at p and extends upward, centered on the dividing line. Each half of that rectangle is a d × d square, and two points on the same side of the line are at least d apart. So each square holds at most 4 points, and the whole rectangle holds at most 8. That means p only has to be compared with the next 7 points in y order. The strip scan is therefore O(n).
Implementation
import math
def closest_pair(points):
# Smallest distance between any two of at least 2 distinct points
px = sorted(points)
py = sorted(points, key=lambda p: p[1])
return _closest(px, py)
def _brute(pts):
best = float('inf')
for i in range(len(pts)):
for j in range(i + 1, len(pts)):
best = min(best, math.dist(pts[i], pts[j]))
return best
def _closest(px, py):
n = len(px)
if n <= 3:
return _brute(px)
mid = n // 2
split = px[mid]
left_y = [p for p in py if p < split]
right_y = [p for p in py if p >= split]
d = min(_closest(px[:mid], left_y), _closest(px[mid:], right_y))
strip = [p for p in py if abs(p[0] - split[0]) < d]
for i in range(len(strip)):
for j in range(i + 1, min(i + 8, len(strip))):
if strip[j][1] - strip[i][1] >= d:
break
d = min(d, math.dist(strip[i], strip[j]))
return d
pts = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print(round(closest_pair(pts), 4)) # 1.4142The list py is sorted by y once, at the top level. Each call splits it in linear time. Points are tuples, so p < split compares them lexicographically, which puts exactly the points in px[:mid] into left_y.
With a linear combine step, the recurrence is T(n) = 2T(n/2) + O(n), which solves to O(n log n), the same as merge sort.
Exercise
Why does the code use the tuple comparison p < split to split py, instead of p[0] < split[0]?
Show answer
Several points can share the median x-coordinate. Splitting by x alone could send a different number of points left than px[:mid] contains, so the two halves would disagree. Lexicographic tuple comparison matches the order of px exactly, as long as the points are distinct.
Exercise
Suppose the combine step compared every strip point with every other strip point. What would the worst-case running time be?
Show answer
All n points can fall inside the strip, so the combine step would cost O(n²). The recurrence T(n) = 2T(n/2) + O(n²) solves to O(n²), which is no better than brute force.