Sub topic 16
Closest Pair of Points in the Plane
This chapter assumes you already know merge sort and its recurrence T(n) = 2T(n/2) + O(n), the crossing-case pattern from the maximum subarray chapter, and the master theorem. The problem is simple to state. You are given n points in the plane. Find the smallest Euclidean distance between any two of them.
Checking every pair takes O(n²) time. Divide and conquer brings this down to O(n log n). The divide step and the recursive step are easy. Most of the work is in the combine step: you have to handle a pair that crosses the split line without examining every crossing pair.
The Shape of the Algorithm
The algorithm follows the same plan as maximum subarray. The closest pair lies entirely in the left half, entirely in the right half, or has one point on each side.
- Divide. Sort the points by x-coordinate and split them at the median x into a left half L and a right half R.
- Conquer. Recursively find the closest distance dL in L and dR in R. Let d = min(dL, dR).
- Combine. Look for a crossing pair closer than d. Return the smaller of that distance and d.
Why the Combine Step Is Linear
A crossing pair closer than d must have both points within horizontal distance d of the split line. If either point were farther away, the x difference alone would already be at least d. So you only need the points in a vertical strip of width 2d centred on the dividing line.
That observation alone does not help, because every point might sit inside the strip. The key fact is a packing argument.
Sort the strip points by y. Take a strip point p. Any partner q above p that is closer than d must lie in a rectangle that is d tall and 2d wide, with p on its bottom edge. Cut this rectangle into eight squares with side d/2: four on the left of the line and four on the right. Each square lies entirely on one side of the line, so any two points in the same square belong to the same half. Points within one half are at least d apart. The diagonal of a small square is d/√2, which is less than d, so a square holds at most one point. The rectangle therefore holds at most 8 points, and one of them is p.
So each strip point only needs to be compared with at most 7 points that follow it in y order. The scan is O(n).
Keeping the Recurrence at O(n log n)
The strip has to be in y order. If you sort it at each level, every combine step costs O(n log n), the recurrence becomes T(n) = 2T(n/2) + O(n log n), and the total is O(n log² n). That is still faster than O(n²), but it is not the optimal bound.
The fix is to sort by y once, at the top. Pass two lists into each call: px, the points sorted by x, and py, the same points sorted by y. When you split, walk through py and send each point to the left or right list. This keeps both sublists in y order in linear time, much like running merge sort's merge in reverse. Each level now does O(n) work:
T(n) = 2T(n/2) + O(n) = O(n log n)
The two initial sorts also cost O(n log n), so they do not change the total.
Implementation
import math
import random
def dist(p, q):
return math.hypot(p[0] - q[0], p[1] - q[1])
def brute_force(pts):
best = float('inf')
for i in range(len(pts)):
for j in range(i + 1, len(pts)):
best = min(best, dist(pts[i], pts[j]))
return best
def closest_pair(points):
# Returns the smallest distance between two of the given (x, y) points.
if len(points) < 2:
raise ValueError("need at least two points")
# Tag each point with its index so duplicates stay distinct.
tagged = [(x, y, i) for i, (x, y) in enumerate(points)]
px = sorted(tagged)
py = sorted(tagged, key=lambda p: p[1])
return _closest(px, py)
def _closest(px, py):
n = len(px)
if n <= 3:
return brute_force(px)
mid = n // 2
split = px[mid]
left_x, right_x = px[:mid], px[mid:]
# Tuples are unique, so comparing with split divides py exactly as px was divided.
left_y = [p for p in py if p < split]
right_y = [p for p in py if p >= split]
d = min(_closest(left_x, left_y), _closest(right_x, right_y))
strip = [p for p in py if abs(p[0] - split[0]) < d]
for i in range(len(strip)):
j = i + 1
while j < len(strip) and strip[j][1] - strip[i][1] < d:
d = min(d, dist(strip[i], strip[j]))
j += 1
return d
pts = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print(round(closest_pair(pts), 4)) # 1.4142
random.seed(1)
for _ in range(200):
sample = [(random.randint(0, 50), random.randint(0, 50)) for _ in range(40)]
assert math.isclose(closest_pair(sample), brute_force(sample))
print("all random tests passed")The inner while loop stops as soon as the y gap reaches d. By the packing argument, it runs at most 7 times per point. Using the y-gap condition instead of a fixed range(i + 1, i + 8) is simpler and always correct. A fixed count of 7 is safe in theory, but it is easy to get off by one.
Edge Cases and Common Errors
| Pitfall | Symptom | Fix |
|---|---|---|
| Sorting the strip at every level | Correct output, but O(n log² n) time | Presort by y once and split `py` in linear time |
| Splitting `py` with `x < mid_x` | Points sharing the median x end up on the wrong side, and the halves no longer match `px` | Compare whole unique tuples, or split by membership in the left half |
| Duplicate points | Set-based splitting drops or merges points | Tag points with their index, as the code does |
| Base case of size 1 | `min` of two infinities, or infinite recursion when n = 2 or 3 | Use brute force for n ≤ 3 |
| Using `<=` in the strip filter | Still correct, but it scans more points | `<` is enough, because only pairs strictly closer than d matter |
| Comparing squared and unsquared distances | Wrong minimum | Use one metric everywhere. Squared distances avoid `sqrt`, but then compare gaps against d² consistently |
Several vertical points with the same x-coordinate are a useful stress test. The median split may fall in the middle of them, and the strip then contains nearly everything. The packing bound still holds, so the scan stays linear.
How This Fits the Larger Pattern
Closest pair uses the crossing-case structure from maximum subarray. In both, the combine step must find answers that cross the split. In maximum subarray, the crossing answer must touch the midpoint, so two linear scans find it. In closest pair, a geometric argument limits how many crossing candidates exist. In both problems, a linear-time combine step is what produces O(n log n). The same idea extends to higher dimensions and appears in computational geometry problems such as finding nearest neighbours.
Exercise
Suppose you skip the presorted py list and instead sort the strip by y inside every recursive call. Write the new recurrence and give its solution.
Show answer
Sorting the strip costs O(n log n) in the worst case, so T(n) = 2T(n/2) + O(n log n). Each of the log n levels of the recursion tree does O(n log n) work, so T(n) = O(n log² n).
Exercise
Why can no small square of side d/2 inside the d by 2d rectangle contain two input points?
Show answer
Each square lies entirely on one side of the split line, so two points in it would belong to the same half. Points in the same half are at least d apart, because d is the minimum of dL and dR. The farthest apart two points in the square can be is its diagonal, d/√2, which is less than d. That is a contradiction.
Exercise
Run closest_pair on [(0, 0), (0, 0), (5, 5)]. What does it return, and which part of the code makes it correct?
Show answer
It returns 0.0. Index tagging keeps the two copies of (0, 0) as separate tuples, so neither is lost. With n = 3, the brute-force base case compares them and finds distance 0.