Closest Pair of Points
Given n points in the plane, find the two that are nearest each other. Brute force checks every pair; divide and conquer gets it down to O(n log n) with one clever observation about a narrow strip.
The Problem and the Brute Force
The closest pair problem: given n points in the plane, find the two with the smallest Euclidean distance √((x₁ − x₂)² + (y₁ − y₂)²).
Brute force computes the distance for every pair, n(n − 1)/2 of them, so it runs in O(n²). For a million points that is about 5 × 10¹¹ distance computations.
The divide-and-conquer method of Shamos and Hoey (1975) solves it in O(n log n), which matches the Ω(n log n) lower bound for this problem in the algebraic decision-tree model. It is one of the standard examples of divide and conquer because its combine step is where all the cleverness lives.
- Fewer than two points: there is no pair, so return nothing
- Duplicate points: the answer is distance 0, and you can stop at once
- Ties: any pair at the smallest distance is a correct answer
- Compare squared distances; take one square root at the end
Worked Example: Why Sorting Alone Is Not Enough
In one dimension it does. Once the values are sorted, the closest pair must be adjacent: any two values with something between them are further apart than one of them is from that middle value. The gaps are 6, 1, 7, 8, so the answer is 9 and 10, found in O(n log n) for the sort plus O(n) for one scan.
- 1D input – values 3, 9, 10, 17, 25 on a line.
- 2D input – P(0, 0), Q(1, 5), R(2, 0).
- Question – does sorting and comparing only neighbours find the closest pair?
In two dimensions it does not. Sorted by x the order is P, Q, R, so the neighbour pairs are P–Q and Q–R, each √26 ≈ 5.10 apart. The closest pair is P–R at 2.0, and P and R are not neighbours in x order. Sorting by one coordinate throws away the information in the other.
That is exactly the gap divide and conquer has to close. After splitting by x, it must still check pairs that straddle the dividing line, and it must do so without comparing every left point with every right point.
- Sorting by y fails the same way: swap each point's x and y
- No single sort order can promise the closest pair are neighbours
- Divide and conquer keeps the x sort and adds one check across the split
Divide, Conquer, Then Check the Strip
- Sort – sort the points by x once, before the recursion.
- Divide – split at the middle point into left and right halves with a vertical line x = m.
- Conquer – recursively find the closest pair in each half: distances δL and δR. Stop at 2 or 3 points and use brute force.
- Set δ – δ = min(δL, δR), the best distance with both points on one side.
- Build the strip – keep only points with |x − m| < δ, ordered by y.
- Scan the strip – compare each point with the following points while their y difference is less than δ, updating δ whenever a closer pair appears.
The correctness argument is short. The closest pair either lies entirely in one half, and the recursion found it, or it crosses the line. A crossing pair closer than δ must have both points within δ of the line, so it lies in the strip, and within the strip the two points differ by less than δ in y, so the scan reaches it.
The y order is what keeps the scan cheap. The fast version returns each half sorted by y and merges the two lists as in merge sort, so no sorting happens inside the recursion.
- Many points with the same x: split by index, not by value, so both halves shrink
- A point exactly on the line may go in either half; the strip catches it either way
- Keep the pair, not only δ, so the answer names the two points
Terms, operations, and practical uses
Core vocabulary
- δThe smallest distance found so far, first from the two halves.
- StripPoints within δ of the dividing line; the only candidates for a crossing pair.
- Packing argumentEight δ/2 squares hold at most one point each, so at most 7 comparisons.
Common mistakes
- Scanning the whole stripStop each scan once the y difference reaches δ.
- Re-sorting by y every callCosts an extra log n; merge instead.
- Forgetting δ can shrinkUpdate δ during the strip scan, not only after it.
Related lessons
- Divide and conquerThe paradigm and the master theorem.
- Merge sortThe same T(n) = 2T(n/2) + O(n) recurrence.
- Time and space complexityWhy O(n log n) beats O(n²) so decisively.
Code in Python, C++ and Java
import math
from heapq import merge
computations = 0
def dist(p, q):
global computations
computations += 1
return math.hypot(p[1] - q[1], p[2] - q[2])
def closest(by_x):
# Returns (distance, pair, points sorted by y).
n = len(by_x)
if n <= 3:
best = (math.inf, None)
for i in range(n):
for j in range(i + 1, n):
d = dist(by_x[i], by_x[j])
if d < best[0]:
best = (d, (by_x[i], by_x[j]))
return best[0], best[1], sorted(by_x, key=lambda p: p[2])
mid = n // 2
mid_x = (by_x[mid - 1][1] + by_x[mid][1]) / 2
d_left, pair_left, left_y = closest(by_x[:mid])
d_right, pair_right, right_y = closest(by_x[mid:])
best, pair = (d_left, pair_left) if d_left <= d_right else (d_right, pair_right)
# Merge the two y-sorted halves in linear time, as in merge sort.
by_y = list(merge(left_y, right_y, key=lambda p: p[2]))
# Only points closer than best to the dividing line can form a better pair.
strip = [p for p in by_y if abs(p[1] - mid_x) < best]
for i in range(len(strip)):
j = i + 1
while j < len(strip) and strip[j][2] - strip[i][2] < best:
d = dist(strip[i], strip[j])
if d < best:
best, pair = d, (strip[i], strip[j])
j += 1
return best, pair, by_y
def show(p):
return f"{p[0]}({p[1]}, {p[2]})"
points = [("A", 10, 70), ("B", 18, 30), ("C", 30, 85), ("D", 42, 50),
("E", 52, 56), ("F", 64, 20), ("G", 78, 72), ("H", 90, 40)]
d, (p, q), _ = closest(sorted(points, key=lambda p: p[1]))
print("closest pair:", show(p), show(q))
print(f"distance: {d:.2f}")
n = len(points)
print(f"distance computations: {computations} (brute force: {n * (n - 1) // 2})")#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iterator>
#include <limits>
#include <string>
#include <vector>
using namespace std;
struct Point {
char name;
double x, y;
};
struct Result {
double best;
Point p, q;
};
int computations = 0;
double dist(const Point& a, const Point& b) {
computations++;
return hypot(a.x - b.x, a.y - b.y);
}
// Solves pts[lo, hi), which is sorted by x, and leaves that range sorted by y.
Result closest(vector<Point>& pts, int lo, int hi) {
Result r{numeric_limits<double>::infinity(), {}, {}};
auto byY = [](const Point& a, const Point& b) { return a.y < b.y; };
if (hi - lo <= 3) {
for (int i = lo; i < hi; i++) {
for (int j = i + 1; j < hi; j++) {
double d = dist(pts[i], pts[j]);
if (d < r.best) r = {d, pts[i], pts[j]};
}
}
sort(pts.begin() + lo, pts.begin() + hi, byY);
return r;
}
int mid = (lo + hi) / 2;
double midX = (pts[mid - 1].x + pts[mid].x) / 2;
Result left = closest(pts, lo, mid), right = closest(pts, mid, hi);
r = left.best <= right.best ? left : right;
// Merge the two y-sorted halves in linear time, as in merge sort.
inplace_merge(pts.begin() + lo, pts.begin() + mid, pts.begin() + hi, byY);
// Only points closer than best to the dividing line can form a better pair.
vector<Point> strip;
for (int i = lo; i < hi; i++) {
if (fabs(pts[i].x - midX) < r.best) strip.push_back(pts[i]);
}
for (size_t i = 0; i < strip.size(); i++) {
for (size_t j = i + 1; j < strip.size() && strip[j].y - strip[i].y < r.best; j++) {
double d = dist(strip[i], strip[j]);
if (d < r.best) r = {d, strip[i], strip[j]};
}
}
return r;
}
int main() {
vector<Point> pts = {{'A', 10, 70}, {'B', 18, 30}, {'C', 30, 85}, {'D', 42, 50},
{'E', 52, 56}, {'F', 64, 20}, {'G', 78, 72}, {'H', 90, 40}};
int n = pts.size();
sort(pts.begin(), pts.end(), [](const Point& a, const Point& b) { return a.x < b.x; });
Result r = closest(pts, 0, n);
printf("closest pair: %c(%g, %g) %c(%g, %g)\n", r.p.name, r.p.x, r.p.y, r.q.name, r.q.x, r.q.y);
printf("distance: %.2f\n", r.best);
printf("distance computations: %d (brute force: %d)\n", computations, n * (n - 1) / 2);
}import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
record Point(char name, double x, double y) {
public String toString() {
return String.format("%c(%.0f, %.0f)", name, x, y);
}
}
record Result(double best, Point p, Point q) {}
static int computations = 0;
static double dist(Point a, Point b) {
computations++;
return Math.hypot(a.x() - b.x(), a.y() - b.y());
}
// Solves pts[lo, hi), which is sorted by x, and leaves that range sorted by y.
static Result closest(Point[] pts, int lo, int hi) {
Comparator<Point> byY = Comparator.comparingDouble(Point::y);
Result r = new Result(Double.POSITIVE_INFINITY, null, null);
if (hi - lo <= 3) {
for (int i = lo; i < hi; i++) {
for (int j = i + 1; j < hi; j++) {
double d = dist(pts[i], pts[j]);
if (d < r.best()) r = new Result(d, pts[i], pts[j]);
}
}
Arrays.sort(pts, lo, hi, byY);
return r;
}
int mid = (lo + hi) / 2;
double midX = (pts[mid - 1].x() + pts[mid].x()) / 2;
Result left = closest(pts, lo, mid), right = closest(pts, mid, hi);
r = left.best() <= right.best() ? left : right;
// Merge the two y-sorted halves in linear time, as in merge sort.
Point[] merged = new Point[hi - lo];
int a = lo, b = mid, k = 0;
while (a < mid || b < hi) {
merged[k++] = b >= hi || (a < mid && pts[a].y() <= pts[b].y()) ? pts[a++] : pts[b++];
}
System.arraycopy(merged, 0, pts, lo, merged.length);
// Only points closer than best to the dividing line can form a better pair.
List<Point> strip = new ArrayList<>();
for (int i = lo; i < hi; i++) {
if (Math.abs(pts[i].x() - midX) < r.best()) strip.add(pts[i]);
}
for (int i = 0; i < strip.size(); i++) {
for (int j = i + 1; j < strip.size() && strip.get(j).y() - strip.get(i).y() < r.best(); j++) {
double d = dist(strip.get(i), strip.get(j));
if (d < r.best()) r = new Result(d, strip.get(i), strip.get(j));
}
}
return r;
}
public static void main(String[] args) {
Point[] pts = {
new Point('A', 10, 70), new Point('B', 18, 30), new Point('C', 30, 85), new Point('D', 42, 50),
new Point('E', 52, 56), new Point('F', 64, 20), new Point('G', 78, 72), new Point('H', 90, 40)
};
int n = pts.length;
Arrays.sort(pts, Comparator.comparingDouble(Point::x));
Result r = closest(pts, 0, n);
System.out.println("closest pair: " + r.p() + " " + r.q());
System.out.printf("distance: %.2f%n", r.best());
System.out.println("distance computations: " + computations + " (brute force: " + n * (n - 1) / 2 + ")");
}
}Step through it
Running on A(10,70) B(18,30) C(30,85) D(42,50) E(52,56) F(64,20) G(78,72) H(90,40)
Why Only 7 Points Are Checked in the Strip
The strip could hold all n points, so a careless scan would still be O(n²). The diagram at the top shows why it is not.
Take a point p in the strip. Any point closer than δ above it lies in a box δ tall and 2δ wide, centred on the line. Split that box into eight squares of side δ/2, four on each side. Two points inside one square would be at most δ/√2 ≈ 0.71δ apart, and on the same side of the line, contradicting the fact that every same-side pair is at least δ apart. So each square holds at most one point, and p needs comparing with at most 7 others.
Tighter packing arguments lower the constant further, but any constant is enough: the strip scan is O(n) per level of recursion.
- Why δ/2: a square's diagonal, δ/√2, is shorter than δ
- The code never counts to 7; the loop stops when Δy reaches δ, and the bound says that happens soon
- Only points above p are checked; pairs with points below were checked from those points
Running Time: O(n log n) or O(n log² n)
Each call does two recursive calls on halves plus linear work: splitting, merging by y, building the strip and scanning it. That gives the recurrence T(n) = 2T(n/2) + O(n), which by the master theorem is O(n log n), the same as merge sort.
A common simpler version sorts the strip by y inside every call. That combine step costs O(n log n), so the recurrence becomes T(n) = 2T(n/2) + O(n log n) = O(n log² n). It is still far better than O(n²), but it is not the optimal algorithm, and exams often ask you to name the difference.
Space is O(n) for the sorted copies, plus O(log n) for the recursion stack.
| Approach | Time | Notes |
|---|---|---|
| Brute force | O(n²) | Every pair; fine for n ≤ a few thousand |
| D&C, strip sorted each call | O(n log² n) | Simpler to code |
| D&C, merge by y | O(n log n) | Optimal; the version on this page |
| Randomised grid (Rabin) | O(n) expected | Hashes points into δ-sized cells |
- The one sort by x before the recursion costs O(n log n) and does not change the bound
- Recursion depth is log n, so the stack stays small
- For a few hundred points brute force is often faster in practice
Applications and Variants
Closest pair is a building block in computational geometry and in any system that watches for things getting too close: collision detection in games and robotics, air-traffic conflict alerts, and the first merge step of hierarchical clustering.
The same divide-and-conquer skeleton works for other distance measures, such as Manhattan distance, and extends to three or more dimensions with a slab instead of a strip. When the points change over time or many nearest-neighbour queries are needed, a spatial index such as a k-d tree is the usual tool instead.
- Collision detection and proximity alerts
- First step of single-linkage clustering
- Works for Manhattan distance and higher dimensions
- For repeated queries, use a spatial index