Divide and Conquer in Geometry
Closest pair of points, convex hulls and their lower bounds.
Given a million points in the plane, which two are closest? Checking every pair means half a trillion distance computations. Shamos and Hoey's 1975 divide-and-conquer algorithm needs , thanks to a packing argument: near the dividing line, each point has at most seven candidates. The same paradigm builds convex hulls, and lower bounds show that cannot be beaten in the usual models of computation.
What you’ll learn
- Design the divide-and-conquer closest-pair algorithm and prove that each strip point has at most 7 candidates.
- Keep the recursion at by merging by , and explain how randomized grid hashing reaches expected time.
- Compute convex hulls with Andrew's monotone chain and by divide and conquer, using exact orientation tests.
- Prove lower bounds by reductions from element distinctness and sorting, and state the output-sensitive hull algorithms.
Closest pair: split, recurse, and a narrow strip
The closest pair problem: given points in the plane, find the smallest distance between two of them. Brute force computes all distances.
Divide and conquer (Shamos & Hoey, 1975): sort the points by and split them at the median into a left half and a right half by a vertical line . Solve both halves recursively, and let be the smaller of the two answers. A pair closer than must then cross the line, and both of its points lie within horizontal distance of it: in the strip .
Points of the same half are at least apart. How many such points, pairwise at least apart, can a closed square contain at most?
Show the answer
4 points
Four, one at each corner. Cut the square into four squares: each has diameter , so it can hold at most one of the points, and four can be achieved.
Every strip point with lies in the rectangle
Its left square can hold at most 4 points of , and its right square at most 4 points of , since points of the same half are at least apart (the prediction above):
Those 8 include itself, and the strip points that follow with all lie in . So there are at most 7 of them, and they come first in order.
import heapq, math
def closest_pair(points): # at least 2 points; returns the smallest distance
def solve(p): # p sorted by x; returns (distance, p sorted by y)
if len(p) <= 3:
d = min((math.dist(a, b) for i, a in enumerate(p) for b in p[i + 1:]), default=math.inf)
return d, sorted(p, key=lambda q: q[1])
mid = len(p) // 2
x_mid = p[mid][0]
dl, left = solve(p[:mid])
dr, right = solve(p[mid:])
d = min(dl, dr)
by_y = list(heapq.merge(left, right, key=lambda q: q[1])) # O(n) merge by y
strip = [q for q in by_y if abs(q[0] - x_mid) < d]
for k, a in enumerate(strip):
for b in strip[k + 1:k + 8]: # at most 7 candidates, by the strip lemma
if b[1] - a[1] >= d:
break
d = min(d, math.dist(a, b))
return d, by_y
return solve(sorted(points))[0]Sorting by once and returning each half sorted by , merged as in merge sort, gives in the worst case. Re-sorting each strip from scratch would give . Points on the dividing line and repeated points are handled correctly.
After the two recursive calls return , why may the algorithm ignore every crossing pair with a point outside the strip ?
- Such pairs were already examined by the recursive calls
- A point outside the strip is at horizontal distance at least from every point on the other side of the line, so its crossing pairs are at least long
- Points outside the strip are too few to matter
- Because the strip contains at most 7 points
Show the answer
B. A point outside the strip is at horizontal distance at least from every point on the other side of the line, so its crossing pairs are at least long
If and lies on the other side, , then . Such a pair cannot beat .
Lower bounds, and beating them with randomness
Lower bound. Closest pair needs operations in the algebraic computation tree model, whose steps are arithmetic operations and comparisons on real numbers. Element distinctness (are all different?) needs there (Ben-Or, 1983), and it reduces to closest pair: map each to the point ; two numbers are equal iff the closest distance is 0.
Beating it. Grant the algorithm the floor function and hashing, and the bound no longer applies. Rabin (1976) and later Khuller and Matias (1995) found expected-time algorithms. The simplest is randomized incremental (Kleinberg & Tardos, §13.7): insert the points in random order, keep the current closest distance and a hash table of grid cells of side . A new point only checks the cells around its own, each holding at most 4 points; if it finds a closer pair, shrinks and the grid is rebuilt.
In a random order, the -th point is a uniformly random one of the first . Fix a closest pair among the first points; changes at step only if the -th point belongs to it:
A change rebuilds the grid of points in expected time; otherwise the insertion costs expected (a constant number of cells, each with at most 4 points):
On 20,000 random points, our implementation rebuilt the grid 17.2 times on average over 5 random orders, in line with the expected number of changes . The algorithm is a Las Vegas algorithm: always correct, randomly fast.
Convex hulls in O(n log n)
The convex hull of a finite point set is the smallest convex polygon that contains it; an algorithm should output its vertices in counterclockwise order. Everything rests on one exact test, the orientation of three points: the sign of is positive if turns left (counterclockwise), negative if it turns right, and zero if the points are collinear.
def cross(o, a, b): # > 0 iff o -> a -> b turns counterclockwise
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def convex_hull(points): # Andrew's monotone chain, counterclockwise
pts = sorted(set(points))
if len(pts) <= 2:
return pts
lower, upper = [], []
for p in pts: # left to right: the lower chain
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
for p in reversed(pts): # right to left: the upper chain
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1] # each chain's last point starts the otherfor the sort, then for the chains: each point is pushed once and popped at most once per chain. Popping on also removes collinear points, so only the corners are output. With integer coordinates the test is exact: for the cross product stays below in absolute value, which fits a signed 64-bit integer in C++.
| Algorithm | Idea | Time |
|---|---|---|
| Gift wrapping (Jarvis, 1973) | from a hull vertex, find the next one by a sweep of orientation tests over all points | for hull vertices |
| Graham's scan (1972) | sort by angle around the lowest point, keep a stack of left turns | |
| Monotone chain (Andrew, 1979) | sort by , build the lower and upper chains with stacks | |
| Divide and conquer (Preparata & Hong, 1977) | hulls of the left and right halves, merged along their upper and lower tangents in | |
| QuickHull | split by the point farthest from a line, recurse on the points outside | fast on typical inputs, in the worst case |
Lower bounds and output sensitivity
Given numbers , lift them onto a parabola:
The parabola is convex, so every is a hull vertex, and walking the hull counterclockwise from the leftmost point visits them in increasing order of . For the monotone chain returns
So a hull algorithm that lists the vertices in order sorts, with extra work, and inherits sorting's lower bound in the algebraic computation tree model (Ben-Or, 1983):
Yao (1981) proved that even identifying the hull vertices, without their order, needs operations in the quadratic decision tree model.
Output sensitivity. When the hull has only vertices, is possible and optimal. Kirkpatrick and Seidel (1986) found the first such algorithm, "marriage before conquest": find the hull edge that crosses the median line before recursing, and discard the points beneath it; they also proved the matching bound. Chan (1996) found a simpler one: guess , split the points into groups of , compute each group's hull with Graham's scan ( in all), then gift-wrap the whole set, finding each next vertex by binary searches for tangents to the group hulls ( per vertex). If the hull does not close within steps, square and start again. With the rounds cost , a geometric series dominated by its last term, .
Key takeaways
- Closest pair: split by , recurse, then check a strip of width in which each point has at most 7 candidates (a packing argument), merging -orders to stay at .
- Element distinctness gives an lower bound in algebraic computation trees; with floor and hashing, randomized incremental grid algorithms run in expected time.
- Convex hulls take with the monotone chain, Graham's scan or divide and conquer, all built on an exact orientation test.
- Sorting reduces to hulls through the parabola , so is optimal in algebraic models; with hull vertices, (Kirkpatrick–Seidel, Chan) is optimal.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does each strip point need to be compared with at most 7 later points in order?
- The strip always contains at most 8 points
- The rectangle of height and width above the point holds at most 4 points of each half, because points of the same half are at least apart
- Because the recursion depth is
- Because each point has at most 7 neighbors in any planar graph
Show the answer
B. The rectangle of height and width above the point holds at most 4 points of each half, because points of the same half are at least apart
Each half of the rectangle splits into four squares of diameter , each holding at most one point of that side. With the point itself, at most 8 points fit, so at most 7 others can be within vertically.
A closest-pair implementation sorts each strip by from scratch in every recursive call, instead of merging -sorted halves. What is its running time?
Show the answer
D.
The combine step now costs , so . Each of the levels costs , for in total. Merging the halves' -orders restores per level.
Why does the expected-time randomized closest-pair algorithm not contradict the lower bound?
- It uses the floor function and hashing to find grid cells, which the algebraic computation tree model does not provide
- The lower bound is only for deterministic algorithms in every model
- Its worst case is also , so the lower bound must be wrong
- The lower bound only applies to points with integer coordinates
Show the answer
A. It uses the floor function and hashing to find grid cells, which the algebraic computation tree model does not provide
Lower bounds hold in a model. Ben-Or's bound counts arithmetic operations and comparisons on reals; computing and hashing cells are not among them, and they let the algorithm bucket points without comparing them, much as counting sort beats the comparison lower bound for sorting.
Which convex-hull bound is never worse than both Graham's and gift wrapping's , where is the number of hull vertices?
- , achieved by Kirkpatrick–Seidel and by Chan
- , achieved by QuickHull
Show the answer
C. , achieved by Kirkpatrick–Seidel and by Chan
Since , ; and . So is at most both bounds, and Kirkpatrick and Seidel proved it optimal as a function of and .
Further reading
- M. I. Shamos & D. Hoey, "Closest-point problems," 16th IEEE Symposium on Foundations of Computer Science (1975).
- M. Ben-Or, "Lower bounds for algebraic computation trees," 15th ACM Symposium on Theory of Computing (1983).
- S. Khuller & Y. Matias, "A simple randomized sieve algorithm for the closest-pair problem," Information and Computation 118(1) (1995), 34–37.
- T. M. Chan, "Optimal output-sensitive convex hull algorithms in two and three dimensions," Discrete & Computational Geometry 16 (1996), 361–368.
- M. de Berg, O. Cheong, M. van Kreveld & M. Overmars, Computational Geometry: Algorithms and Applications, 3rd ed. (Springer, 2008), chapter 1.