Closest Pair of Points Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Closest Pair of Points runs in O(n log n) time and O(n) space, in TypeScript as in every other language.
- ✓TypeScript ships no runtime, so the API is the JavaScript one: sort(compareFn?: (a: T, b: T) => number) from lib.es5.d.ts - ES2019 made it stable at runtime but did not change the signature - Math.hypot from lib.es2015.core.d.ts, and number for every coordinate, with no float-versus-int distinction in the type system to lean on.
- ✓Reviewers insist the two sorted views are different types rather than two variables both typed Point[], because the entire algorithm is a claim about which order each array is in.
- ✓The TypeScript trap: Structural typing cannot see order. { x: number; y: number } is the same type whether the array is sorted by x or by y, so swapping the arguments of solve(px, py) type-checks perfectly and returns a finite, wrong distance - the exact silent failure this topic is famous for, and the checker will never flag it unless you brand the arrays.
- ✓Types erase, so none of this costs anything at runtime - but the shapes you pick do. readonly buys no optimisation; the engine still sees an ordinary mutable object.
What Closest Pair of Points actually is
Closest Pair of Points in TypeScript: what you actually reach for
TypeScript implementation
export interface Point { readonly x: number; readonly y: number }
type SortedBy<K extends 'x' | 'y'> = readonly Point[] & { readonly __by: K };
export interface Best { d: number; a: Point; b: Point }
// The two brand helpers are the only place an assertion is allowed.
const brandX = (ps: readonly Point[]): SortedBy<'x'> => ps as unknown as SortedBy<'x'>;
const brandY = (ps: readonly Point[]): SortedBy<'y'> => ps as unknown as SortedBy<'y'>;
const byX = (ps: readonly Point[]): SortedBy<'x'> =>
brandX([...ps].sort((a, b) => a.x - b.x || a.y - b.y));
const byY = (ps: readonly Point[]): SortedBy<'y'> =>
brandY([...ps].sort((a, b) => a.y - b.y));
export function closestPair(pts: readonly Point[]): Best | null {
return pts.length < 2 ? null : solve(byX(pts), byY(pts));
}
// px and py cannot be swapped: the brands are distinct types.
function solve(px: SortedBy<'x'>, py: SortedBy<'y'>): Best {
const n = px.length;
let best: Best = { d: Infinity, a: px[0]!, b: px[0]! };
if (n <= 3) {
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++) {
const a = px[i]!, b = px[j]!;
const d = Math.hypot(a.x - b.x, a.y - b.y);
if (d < best.d) best = { d, a, b };
}
return best;
}
const mid = n >> 1, splitX = px[mid]!.x;
const left = new Set(px.slice(0, mid));
// A slice of an x-sorted array is still x-sorted: re-brand, never re-sort.
const l = solve(brandX(px.slice(0, mid)), brandY(py.filter((p) => left.has(p))));
const r = solve(brandX(px.slice(mid)), brandY(py.filter((p) => !left.has(p))));
best = l.d <= r.d ? l : r;
const strip = py.filter((p) => Math.abs(p.x - splitX) < best.d);
for (let i = 0; i < strip.length; i++)
for (let j = i + 1; j < strip.length; j++) {
const a = strip[i]!, b = strip[j]!;
if (b.y - a.y >= best.d) break;
const d = Math.hypot(a.x - b.x, a.y - b.y);
if (d < best.d) best = { d, a, b };
}
return best;
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Closest Pair of Points?
TypeScript ships no runtime, so the API is the JavaScript one: sort(compareFn?: (a: T, b: T) => number) from lib.es5.d.ts - ES2019 made it stable at runtime but did not change the signature - Math.hypot from lib.es2015.core.d.ts, and number for every coordinate, with no float-versus-int distinction in the type system to lean on. What TypeScript adds is that the algorithm's invariants become checkable: interface Point { readonly x: number; readonly y: number }, readonly Point[] for inputs you promise not to mutate, and a branded alias such as type SortedBy<K> = readonly Point[] & { readonly __by: K } that only your own sorting helper can produce.
What is the most common TypeScript mistake when implementing Closest Pair of Points?
Structural typing cannot see order. { x: number; y: number } is the same type whether the array is sorted by x or by y, so swapping the arguments of solve(px, py) type-checks perfectly and returns a finite, wrong distance - the exact silent failure this topic is famous for, and the checker will never flag it unless you brand the arrays. The second is noUncheckedIndexedAccess: it retypes strip[j] as Point | undefined, and the reflexive fix of adding ! throws the guarantee away precisely where the off-by-one in the bounded successor scan lives.
How does Closest Pair of Points actually perform in TypeScript?
Types erase, so none of this costs anything at runtime - but the shapes you pick do. readonly buys no optimisation; the engine still sees an ordinary mutable object. The brand is free for the same reason, which is exactly why the halves are re-branded rather than re-sorted: a slice of an x-sorted array is still x-sorted, and re-minting the brand costs nothing where a second sort would cost O(k log k) at every level. A const enum still compiles under isolatedModules, but it stops being free - TypeScript emits it as an ordinary enum object instead of inlining the members, and declare const enum is a hard error (TS2748); a string-literal union for an axis tag compiles to nothing in every configuration. Down-level compilation keeps for (const p of strip) as an index loop over the array, but turn on downlevelIteration, or iterate something that is not an array or string, and the emit switches to the __values iterator protocol, allocating a { value, done } result object per step. An explicit index loop in the inner scan is immune to that flag. Time complexity is O(n log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.