Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Closest Pair of Points Implementation in TypeScript

19 min readadvanced
Website QA and SEO audits

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

Given n points in the plane, the closest pair is the two with the smallest Euclidean distance between them. Brute force is O(n^2); the divide-and-conquer solution sorts by x, splits at the median, recurses on both halves, then repairs the boundary by scanning a vertical strip of width 2d ordered by y, where each point only has to be compared with a constant number of successors. Working engineers reach for it in collision detection, de-duplicating GPS fixes, seeding clusters and validating meshes, usually as the exact check sitting behind a spatial index.

Closest Pair of Points in TypeScript: what you actually reach for

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.

TypeScript implementation

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. They reject any in the recursion's return type and want a named interface Best { d: number; a: Point; b: Point }. They also reject a scattering of non-null assertions added purely to silence noUncheckedIndexedAccess - the fix is one narrow helper or an index loop that the checker can follow.
typescript
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 Free

The TypeScript-specific 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. 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.

Performance in TypeScript, beyond the O(n log n)

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. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Closest Pair of Points between languages.

Real-World Applications

Closest Pair of Points applies wherever its problem shape appears in your own code. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Closest Pair of Points helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Closest Pair of Points appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Closest Pair of Points over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Closest Pair of Points to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.