Skip to the workspace
Pebellslearn by building
Computational Geometry  ›  Lesson

Closest Pair of Points

Closest Pair 32 minSplit the points by x, solve each half recursively, then check only a narrow strip around the dividing line for a pair closer than the best either half found alone — the strip trick turns an O(n^2) scan into O(n log n)

dsa / Closest Pair of Points

Explore each scene at your own pace.

01 · Two stops near the depot

Two stops near the depot

Closest Pair of Points

Definition
The closest pair of points problem asks for the two nearest points in a set; the divide-and-conquer solution splits the points by x, solves each half, then checks only a narrow strip around the split, giving O(n log n) time overall.
In plain words
To find the two nearest shops on a map, split the map down the middle and find the closest pair on each side. Then look only at the thin band beside the dividing line, where a closer pair could still be hiding.

In short: finding the two closest points among n by checking every pair is O(n²). Divide and conquer brings it to O(n log n): sort by x, split in half, find the closest pair in each half recursively, and keep the smaller distance as best. The only question left is whether some pair straddles the dividing line and beats best — and that can only happen within a narrow strip of width 2 * best around the line. Sort that strip by y, and for each point in it, only the next 7 points in y-order could possibly be close enough to matter. That bound turns an O(n²) strip check into O(n), so the whole algorithm is O(n log n): one sort, then a recursion whose merge step is linear.

A vertical dividing line splitting a cluster of points into a left half and a right half, with a shaded strip of width 2 delta straddling the line, two points inside the strip connected by a dashed line labelled as the pair that beats both halves' separate best distances

Two stops near the depot

Eight of Meridian's stops are scattered around a depot. Which two sit closest together?

step through it
1import math
2 
3def dist2(a, b):
4 return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
5 
6def brute_force_closest(points):
7 best = None
8 best_d = float("inf")
9 n = len(points)
10 for i in range(n):
11 for j in range(i + 1, n):
12 d = dist2(points[i], points[j])
13 if d < best_d:
14 best_d = d
15 best = (points[i], points[j])
16 return best, best_d
17 
18def closest_in_strip(strip_sorted_by_y, best_d, best_pair):
19 n = len(strip_sorted_by_y)
20 for i in range(n):
21 for j in range(i + 1, min(i + 8, n)):
22 d = dist2(strip_sorted_by_y[i], strip_sorted_by_y[j])
23 if d < best_d:
24 best_d = d
25 best_pair = (strip_sorted_by_y[i], strip_sorted_by_y[j])
26 return best_pair, best_d
27 
28def closest_pair_rec(points_sorted_by_x):
29 n = len(points_sorted_by_x)
30 if n <= 3:
31 return brute_force_closest(points_sorted_by_x)
32 mid = n // 2
33 mid_x = points_sorted_by_x[mid][0]
34 left, right = points_sorted_by_x[:mid], points_sorted_by_x[mid:]
35 pair_l, d_l = closest_pair_rec(left)
36 pair_r, d_r = closest_pair_rec(right)
37 best_pair, best_d = (pair_l, d_l) if d_l < d_r else (pair_r, d_r)
38 delta = math.sqrt(best_d)
39 strip = [p for p in points_sorted_by_x if abs(p[0] - mid_x) < delta]
40 strip.sort(key=lambda p: p[1])
41 return closest_in_strip(strip, best_d, best_pair)
42 
43def closest_pair(points):
44 pts = sorted(set(points))
45 pair, d2 = closest_pair_rec(pts)
46 return pair, round(math.sqrt(d2), 4)
47 
48stops = [(0, 0), (6, 1), (3, 4), (9, 0), (1, 1), (8, 8), (5, 5), (2, 7)]
49print(closest_pair(stops))

(0,0) and (1,1) turn out to be the closest pair — a distance of sqrt(2) ≈ 1.4142 — and the brute-force base case finds them directly, because with 8 points the recursion's two halves (4 points each) both bottom out at the n <= 3 base case almost immediately.

Scene 1 of 6
Project context and further resources
You're building a piece ofMeridian — service areas & coverage
This piece — closest_pair(): Finds the two closest stops in a batch in O(n log n), for spacing and merge checks.
Scenario Meridian wants to know, out of a whole batch of stops, which two sit closest together — useful for flagging a possible duplicate stop or checking two hubs aren't placed dangerously close.
closest_pair.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
closest_pair(points) → listThe closest pair of points and their straight-line distance, rounded to 4 decimal places.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.