Closest pair of points: fewer distance checks
Which two points are closest to each other? Check every pair, then find the same minimum by splitting the problem and inspecting a narrow boundary strip.
Video walkthrough
Which two points are closest?
Place points on a board and look for the shortest segment joining two different input items. We use straight-line Euclidean distance. The task returns one pair, rather than a nearest neighbour for every point or a path visiting all points.
In the twelve-point example, E=(48,35) and F=(52,37) lie on opposite sides of x=50. Their distance is √((52−48)²+(37−35)²)=√20≈4.472. Solving each half separately is not enough: the answer can cross the dividing line.
Brute force: check every pair
Try A–B, A–C and the rest, keeping the shortest distance found. Never compare a point with itself and never check both A–B and B–A. For n points there are n(n−1)/2 unordered pairs: 66 for twelve points and 4,950 for a hundred.
The yellow dashed segment is the candidate being measured. Green marks the best pair among the measurements already processed; it becomes the answer only when the whole search finishes. The two methods use the same input, but their steps and ties need not match.
Divide by count, then combine
Sort input identities once by x, breaking ties by y and then identity. Also create a list sorted by y. Split the x-ordered list into two balanced halves. Equal x coordinates may appear in both halves: membership follows identity, not a test x < split. Filter the y list by that same membership so its order is preserved.
Solve each half recursively. A subset of two or three points uses brute force. Choose the shorter of the two answers and call its distance δ₀. A dashed vertical line marks the current split; dimmed points belong to other subproblems. The blue pair is the answer of the current subproblem, which may differ from the globally best green pair.
Only a narrow strip can improve the answer
A cross-boundary pair shorter than δ₀ must have both endpoints less than δ₀ from the split line. Keep those points in a strip of total width 2δ₀, already ordered by y. For each point, inspect at most the next seven positions, stopping earlier when the y gap is at least the current best distance.
Why only seven? Each half already has no pair closer than δ₀. In a 2δ₀-by-δ₀ window, divide each half into four δ₀/2 squares. Each square on either side can contain at most one point of that half, since its diagonal is shorter than δ₀. At most eight points fit in the window, including the current point. The identity partition also covers equal-x points on the split.
The shaded strip keeps its initial width δ₀ during this combine step. A better candidate can reduce the search bound without rebuilding the strip. The implementation may remeasure same-half pairs in the strip; these checks count too. A zero distance is optimal, so that subproblem needs no further strip search.
What makes the answer correct
Every completed recursive call returns a minimum-distance pair in exactly its own subset. Any pair is either entirely in the left half, entirely in the right half, or crosses the split. The recursive answers cover the first two cases; the strip search finds every crossing pair that could strictly improve them.
Strict strip and y-gap tests may omit pairs at exactly the current minimum distance. This is intentional: the task asks for one minimum pair, not every tied pair. On equal distances the existing answer is retained, and the left answer wins a tie between halves. Each method is deterministic for a fixed input order, but the two methods can return different valid pairs.
Coincident points, exact tests and editing
The player accepts 2–24 points, x from 0 to 100 and y from 0 to 70, rounded to one decimal place. Different input items may occupy the same coordinates; their distance is zero. Labels identify input items, not unique locations. The coincident-point preset demonstrates this case.
Distance comparisons use squared distances in integer tenths. Their largest possible value here is 1,490,000, exactly representable by JavaScript Number. Square roots are used only for labels, rounded to three decimal places. A small displayed difference or equal rounded labels do not change the exact integer comparison.
Drag a point or use the coordinate editor. The finished answer remains visible after a valid edit; Restart opens the new search. Invalid input preserves the previous valid example and playback position. Removing a point relabels the remaining input. A share link stores coordinates, method, speed and playback position.
Distance checks, runtime and stored history
Brute force performs exactly n(n−1)/2 distance evaluations: O(n²) time and O(1) working memory once the input exists. The divide-and-conquer core uses balanced recursion, linear filtering and at most seven strip candidates per point, giving O(n log n) time with O(n) peak extra memory when presorting costs O(n log n). The sample uses built-in JavaScript sort, whose cost depends on the engine.
Input validation, normalization and input-index arrays in the wrapper take an additional O(n) space. The counter counts squared Euclidean distance evaluations only. It excludes sorting comparisons, coordinate tests for strip membership and y-gap tests. Full-run totals compare both methods on the current points; they are not a stopwatch or a promise that the recursive method wins on every small input.
The player stores immutable snapshots for stepping backwards and seeking. Copying subset and strip arrays adds costs beyond the algorithm core: at most O(n²) history time and space for this recursive visualization, and O(n³) for brute force, which copies the n-item context for every tested pair. The 24-point limit keeps both histories and labels manageable.
Executable code matching the player
This function applies the same validation, rounding, identity ordering, strict tests and tie choices as the interactive model. It returns zero-based input indices, distance and number of distance evaluations. Drawing and stored animation snapshots are omitted.
Show the executable model
function closestPair(raw, mode = "divide") {
if (!["divide", "brute"].includes(mode) || !Array.isArray(raw) ||
raw.length < 2 || raw.length > 24) throw Error("Invalid input");
const p = raw.map(q => {
if (!q || typeof q.x !== "number" || typeof q.y !== "number" ||
!Number.isFinite(q.x + q.y) || q.x < 0 || q.x > 100 ||
q.y < 0 || q.y > 70) throw Error("Invalid point");
return { x: Math.round(q.x * 10), y: Math.round(q.y * 10) };
});
let checks = 0;
function test(a, b, best) {
checks++;
const squared = (p[a].x - p[b].x) ** 2 + (p[a].y - p[b].y) ** 2;
return !best || squared < best.squared
? { a: Math.min(a, b), b: Math.max(a, b), squared } : best;
}
function brute(ids) {
let best = null;
for (let i = 0; i < ids.length; i++)
for (let j = i + 1; j < ids.length; j++)
best = test(ids[i], ids[j], best);
return best;
}
function solve(xs, ys) {
if (xs.length <= 3) return brute(xs);
const mid = Math.floor(xs.length / 2);
const left = xs.slice(0, mid), right = xs.slice(mid);
const members = new Set(left);
const a = solve(left, ys.filter(id => members.has(id)));
const b = solve(right, ys.filter(id => !members.has(id)));
let best = a.squared <= b.squared ? a : b;
if (best.squared === 0) return best;
const splitTwice = p[left[left.length - 1]].x + p[right[0]].x;
const strip = ys.filter(id =>
(2 * p[id].x - splitTwice) ** 2 < 4 * best.squared);
for (let i = 0; i < strip.length && best.squared > 0; i++) {
for (let j = i + 1; j < strip.length && j <= i + 7; j++) {
const dy = p[strip[j]].y - p[strip[i]].y;
if (dy * dy >= best.squared) break;
best = test(strip[i], strip[j], best);
}
}
return best;
}
const ids = p.map((_, i) => i);
let best;
if (mode === "brute") best = brute(ids);
else {
const xs = [...ids].sort((a, b) => p[a].x - p[b].x || p[a].y - p[b].y || a - b);
const ys = [...ids].sort((a, b) => p[a].y - p[b].y || p[a].x - p[b].x || a - b);
best = solve(xs, ys);
}
return { pair: [best.a, best.b], distance: Math.sqrt(best.squared) / 10, checks };
}