Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 O(nlog⁡n)O(n \log n), 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 nlog⁡nn \log n 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 O(nlog⁡n)O(n \log n) by merging by yy, and explain how randomized grid hashing reaches O(n)O(n) expected time.
  • Compute convex hulls with Andrew's monotone chain and by divide and conquer, using exact orientation tests.
  • Prove Ω(nlog⁡n)\Omega(n \log n) lower bounds by reductions from element distinctness and sorting, and state the output-sensitive O(nlog⁡h)O(n \log h) hull algorithms.

Closest pair: split, recurse, and a narrow strip

The closest pair problem: given n≥2n \ge 2 points in the plane, find the smallest distance between two of them. Brute force computes all n(n−1)/2n(n-1)/2 distances.

Divide and conquer (Shamos & Hoey, 1975): sort the points by xx and split them at the median into a left half PLP_L and a right half PRP_R by a vertical line x=xℓx = x_\ell. Solve both halves recursively, and let δ\delta be the smaller of the two answers. A pair closer than δ\delta must then cross the line, and both of its points lie within horizontal distance δ\delta of it: in the strip ∣x−xℓ∣<δ|x - x_\ell| < \delta.

Predict before you look

Points of the same half are at least δ\delta apart. How many such points, pairwise at least δ\delta apart, can a closed δ×δ\delta \times \delta square contain at most?

Show the answer

4 points

Four, one at each corner. Cut the square into four δ2×δ2\tfrac\delta2 \times \tfrac\delta2 squares: each has diameter δ/2<δ\delta / \sqrt 2 < \delta, so it can hold at most one of the points, and four can be achieved.

DerivationProof
  1. Q=[xℓ−δ, xℓ+δ]×[ya, ya+δ]Q = [x_\ell - \delta,\ x_\ell + \delta] \times [y_a,\ y_a + \delta]

    Every strip point bb with ya≤yb<ya+δy_a \le y_b < y_a + \delta lies in the 2δ×δ2\delta \times \delta rectangle

  2. ∣Q∩(PL∪PR)∣ ≤ 4+4=8|Q \cap (P_L \cup P_R)|\ \le\ 4 + 4 = 8

    Its left δ×δ\delta \times \delta square can hold at most 4 points of PLP_L, and its right square at most 4 points of PRP_R, since points of the same half are at least δ\delta apart (the prediction above):

  3. #{ b after a:yb−ya<δ } ≤ 7\#\{\, b \text{ after } a : y_b - y_a < \delta \,\}\ \le\ 7

    Those 8 include aa itself, and the strip points that follow aa with y<ya+δy < y_a + \delta all lie in QQ. So there are at most 7 of them, and they come first in yy order.

python
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 xx once and returning each half sorted by yy, merged as in merge sort, gives T(n)=2T(n/2)+O(n)=O(nlog⁡n)T(n) = 2T(n/2) + O(n) = O(n \log n) in the worst case. Re-sorting each strip from scratch would give T(n)=2T(n/2)+O(nlog⁡n)=O(nlog⁡2n)T(n) = 2T(n/2) + O(n \log n) = O(n \log^2 n). Points on the dividing line and repeated points are handled correctly.

Check your understanding

After the two recursive calls return δ\delta, why may the algorithm ignore every crossing pair with a point outside the strip ∣x−xℓ∣<δ|x - x_\ell| < \delta?

  1. Such pairs were already examined by the recursive calls
  2. A point outside the strip is at horizontal distance at least δ\delta from every point on the other side of the line, so its crossing pairs are at least δ\delta long
  3. Points outside the strip are too few to matter
  4. Because the strip contains at most 7 points
Show the answer

B. A point outside the strip is at horizontal distance at least δ\delta from every point on the other side of the line, so its crossing pairs are at least δ\delta long

If xa≤xℓ−δx_a \le x_\ell - \delta and bb lies on the other side, xb≥xℓx_b \ge x_\ell, then ∥a−b∥≥xb−xa≥δ\lVert a - b \rVert \ge x_b - x_a \ge \delta. Such a pair cannot beat δ\delta.

Lower bounds, and beating them with randomness

Lower bound. Closest pair needs Ω(nlog⁡n)\Omega(n \log n) operations in the algebraic computation tree model, whose steps are arithmetic operations and comparisons on real numbers. Element distinctness (are x1,…,xnx_1, \dots, x_n all different?) needs Ω(nlog⁡n)\Omega(n \log n) there (Ben-Or, 1983), and it reduces to closest pair: map each xix_i to the point (xi,0)(x_i, 0); 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 O(n)O(n) expected-time algorithms. The simplest is randomized incremental (Kleinberg & Tardos, §13.7): insert the points in random order, keep the current closest distance δ\delta and a hash table of grid cells of side δ\delta. A new point only checks the 3×33 \times 3 cells around its own, each holding at most 4 points; if it finds a closer pair, δ\delta shrinks and the grid is rebuilt.

DerivationExpected O(n) time by backwards analysis
  1. Pr⁡[δ changes at step i] ≤ 2i\Pr\big[\delta \text{ changes at step } i\big]\ \le\ \frac{2}{i}

    In a random order, the ii-th point is a uniformly random one of the first ii. Fix a closest pair among the first ii points; δ\delta changes at step ii only if the ii-th point belongs to it:

  2. E[time] ≤ ∑i=2n(O(1)+2i⋅O(i)) = O(n)\mathbb E[\text{time}]\ \le\ \sum_{i=2}^{n} \Big(O(1) + \frac{2}{i} \cdot O(i)\Big)\ =\ O(n)

    A change rebuilds the grid of ii points in O(i)O(i) expected time; otherwise the insertion costs O(1)O(1) 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 ∑i2/i≈2ln⁡n≈19.8\sum_i 2/i \approx 2 \ln n \approx 19.8. 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 (ax−ox)(by−oy)−(ay−oy)(bx−ox)(a_x - o_x)(b_y - o_y) - (a_y - o_y)(b_x - o_x) is positive if o→a→bo \to a \to b turns left (counterclockwise), negative if it turns right, and zero if the points are collinear.

python
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 other

O(nlog⁡n)O(n \log n) for the sort, then O(n)O(n) for the chains: each point is pushed once and popped at most once per chain. Popping on ≤0\le 0 also removes collinear points, so only the corners are output. With integer coordinates the test is exact: for ∣x∣,∣y∣≤109|x|, |y| \le 10^9 the cross product stays below 8×10188 \times 10^{18} in absolute value, which fits a signed 64-bit integer in C++.

AlgorithmIdeaTime
Gift wrapping (Jarvis, 1973)from a hull vertex, find the next one by a sweep of orientation tests over all pointsO(nh)O(nh) for hh hull vertices
Graham's scan (1972)sort by angle around the lowest point, keep a stack of left turnsO(nlog⁡n)O(n \log n)
Monotone chain (Andrew, 1979)sort by xx, build the lower and upper chains with stacksO(nlog⁡n)O(n \log n)
Divide and conquer (Preparata & Hong, 1977)hulls of the left and right halves, merged along their upper and lower tangents in O(n)O(n)O(nlog⁡n)O(n \log n)
QuickHullsplit by the point farthest from a line, recurse on the points outsidefast on typical inputs, Θ(n2)\Theta(n^2) in the worst case

Lower bounds and output sensitivity

DerivationSorting reduces to convex hulls
  1. xi ↦ pi=(xi, xi2)x_i\ \mapsto\ p_i = (x_i,\ x_i^2)

    Given numbers x1,…,xnx_1, \dots, x_n, lift them onto a parabola:

  2. (−3,9) → (0,0) → (2,4) → (5,25) → (8,64)(-3, 9)\ \to\ (0, 0)\ \to\ (2, 4)\ \to\ (5, 25)\ \to\ (8, 64)

    The parabola is convex, so every pip_i is a hull vertex, and walking the hull counterclockwise from the leftmost point visits them in increasing order of xx. For 5,−3,8,0,25, -3, 8, 0, 2 the monotone chain returns

  3. Thull(n)+O(n) ≥ Tsort(n)=Ω(nlog⁡n)T_{\text{hull}}(n) + O(n)\ \ge\ T_{\text{sort}}(n) = \Omega(n \log n)

    So a hull algorithm that lists the vertices in order sorts, with O(n)O(n) 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 Ω(nlog⁡n)\Omega(n \log n) operations in the quadratic decision tree model.

Output sensitivity. When the hull has only hh vertices, O(nlog⁡h)O(n \log h) 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 Ω(nlog⁡h)\Omega(n \log h) bound. Chan (1996) found a simpler one: guess mm, split the points into ⌈n/m⌉\lceil n/m \rceil groups of mm, compute each group's hull with Graham's scan (O(nlog⁡m)O(n \log m) in all), then gift-wrap the whole set, finding each next vertex by binary searches for tangents to the group hulls (O((n/m)log⁡m)O((n/m) \log m) per vertex). If the hull does not close within mm steps, square mm and start again. With m=22tm = 2^{2^t} the rounds cost O(n⋅2t)O(n \cdot 2^t), a geometric series dominated by its last term, O(nlog⁡h)O(n \log h).

Key takeaways

  • Closest pair: split by xx, recurse, then check a strip of width 2δ2\delta in which each point has at most 7 candidates (a packing argument), merging yy-orders to stay at O(nlog⁡n)O(n \log n).
  • Element distinctness gives an Ω(nlog⁡n)\Omega(n \log n) lower bound in algebraic computation trees; with floor and hashing, randomized incremental grid algorithms run in O(n)O(n) expected time.
  • Convex hulls take O(nlog⁡n)O(n \log n) 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 y=x2y = x^2, so O(nlog⁡n)O(n \log n) is optimal in algebraic models; with hh hull vertices, O(nlog⁡h)O(n \log h) (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.

Question 1

Why does each strip point need to be compared with at most 7 later points in yy order?

  1. The strip always contains at most 8 points
  2. The rectangle of height δ\delta and width 2δ2\delta above the point holds at most 4 points of each half, because points of the same half are at least δ\delta apart
  3. Because the recursion depth is log⁡2n\log_2 n
  4. Because each point has at most 7 neighbors in any planar graph
Show the answer

B. The rectangle of height δ\delta and width 2δ2\delta above the point holds at most 4 points of each half, because points of the same half are at least δ\delta apart

Each δ×δ\delta \times \delta half of the rectangle splits into four squares of diameter δ/2<δ\delta/\sqrt 2 < \delta, 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 δ\delta vertically.

Question 2

A closest-pair implementation sorts each strip by yy from scratch in every recursive call, instead of merging yy-sorted halves. What is its running time?

  1. O(n2)O(n^2)
  2. O(nlog⁡n)O(n \log n)
  3. O(n)O(n)
  4. O(nlog⁡2n)O(n \log^2 n)
Show the answer

D. O(nlog⁡2n)O(n \log^2 n)

The combine step now costs O(nlog⁡n)O(n \log n), so T(n)=2T(n/2)+O(nlog⁡n)T(n) = 2T(n/2) + O(n \log n). Each of the log⁡n\log n levels costs O(nlog⁡n)O(n \log n), for O(nlog⁡2n)O(n \log^2 n) in total. Merging the halves' yy-orders restores O(n)O(n) per level.

Question 3

Why does the O(n)O(n) expected-time randomized closest-pair algorithm not contradict the Ω(nlog⁡n)\Omega(n \log n) lower bound?

  1. It uses the floor function and hashing to find grid cells, which the algebraic computation tree model does not provide
  2. The lower bound is only for deterministic algorithms in every model
  3. Its worst case is also O(n)O(n), so the lower bound must be wrong
  4. 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 ⌊x/δ⌋\lfloor x / \delta \rfloor 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.

Question 4

Which convex-hull bound is never worse than both Graham's O(nlog⁡n)O(n \log n) and gift wrapping's O(nh)O(nh), where hh is the number of hull vertices?

  1. O(n+h2)O(n + h^2)
  2. O(hlog⁡n)O(h \log n)
  3. O(nlog⁡h)O(n \log h), achieved by Kirkpatrick–Seidel and by Chan
  4. O(n)O(n), achieved by QuickHull
Show the answer

C. O(nlog⁡h)O(n \log h), achieved by Kirkpatrick–Seidel and by Chan

Since h≤nh \le n, log⁡h≤log⁡n\log h \le \log n; and log⁡h≤h\log h \le h. So nlog⁡hn \log h is at most both bounds, and Kirkpatrick and Seidel proved it optimal as a function of nn and hh.

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.