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

Convex Hull 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

  • ✓Convex Hull runs in O(n log n) time and O(n) space, in TypeScript as in every other language.
  • ✓TypeScript adds no runtime, so the machinery is the same Array.prototype.sort with push and pop.
  • ✓Reviewers want the tuple type rather than number[], and readonly on every input array so the function provably cannot sort in place.
  • ✓The TypeScript trap: Types are erased, so the one place they cannot help is the boundary -- and this algorithm lives at one.
  • ✓Types cost nothing at runtime, but the emit does. for (const p of seq) compiled against an ES5 target with downlevelIteration becomes a helper that allocates an iterator object per call; target ES2015 or later and the allocation disappears.

What Convex Hull actually is

The convex hull of a point set is the smallest convex polygon containing every point: the shape a rubber band snaps to. The divide-and-conquer form sorts by x, hulls each half recursively, then stitches the halves with an upper and a lower tangent in linear time, giving O(n log n) worst case. Quickhull is the other divide step (average O(n log n), worst O(n^2)). Engineers reach for a hull in collision broad-phase, GIS footprints, outlier boundaries, and as step one of rotating calipers for diameter, min-width and min-area rectangle. Andrew's monotone chain -- sort once, then two linear scans -- hits the same bound with a far simpler merge, and is what most production code actually ships.

Convex Hull in TypeScript: what you actually reach for

TypeScript adds no runtime, so the machinery is the same Array.prototype.sort with push and pop. What it adds is shape: type Point = readonly [x: number, y: number], a labelled tuple, or a readonly { x: number; y: number } interface, so the compiler stops you handing in a number[] of unknown length. On DefinitelyTyped, @types/d3-polygon declares polygonHull as taking an array of [number, number] pairs and returning that array type or null. The | null is what makes the typed binding worth using: it forces the degenerate fewer-than-three case to be handled at compile time.

TypeScript implementation

Reviewers want the tuple type rather than number[], and readonly on every input array so the function provably cannot sort in place. Under noUncheckedIndexedAccess, h[h.length - 2] is Point | undefined; the accepted answer is h.at(-2) with an explicit undefined guard, and a non-null assertion in the pop loop gets flagged every single time. Anything arriving from JSON.parse or fetch has to pass a runtime validator before it is allowed to be typed as Point[].
typescript
export type Point = readonly [x: number, y: number];

const cross = (o: Point, a: Point, b: Point): number =>
  (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);

function chain(seq: readonly Point[]): Point[] {
  const h: Point[] = [];
  for (const p of seq) {
    for (;;) {
      const a = h.at(-2);
      const b = h.at(-1);
      // .at() always returns Point | undefined (lib.es2022); h[h.length - 2]
      // only does under noUncheckedIndexedAccess. Either way: no `!`.
      if (a === undefined || b === undefined) break;
      if (cross(a, b, p) > 0) break;
      h.pop();
    }
    h.push(p);
  }
  h.pop();
  return h;
}

export function convexHull(points: readonly Point[]): Point[] {
  const pts = [...points].sort((p, q) => p[0] - q[0] || p[1] - q[1]);
  if (pts.length < 3) return pts;
  return [...chain(pts), ...chain([...pts].reverse())];
}

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

Types are erased, so the one place they cannot help is the boundary -- and this algorithm lives at one. JSON.parse returns any, so const pts = JSON.parse(body) as Point[] type-checks perfectly while handing you objects, strings, or two-element arrays that are actually one element long. A missing second slot makes p[1] undefined, the cross product becomes NaN, and NaN in a comparator is the worst possible value: it is neither negative, zero nor positive, so sort produces an arbitrary permutation instead of throwing. The hull comes out wrong with no stack trace anywhere in it. Validate at the edge with zod or a hand-written type guard; as is not validation.

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

Types cost nothing at runtime, but the emit does. for (const p of seq) compiled against an ES5 target with downlevelIteration becomes a helper that allocates an iterator object per call; target ES2015 or later and the allocation disappears. Spreads such as [...pts].reverse() lower to __spreadArray under old targets, copying twice instead of once. const enum inlines but breaks under isolatedModules, so most codebases forbid it. Everything else -- hidden classes, comparator monomorphism, packed-array behaviour -- is V8's, and is identical to plain JavaScript. 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 Convex Hull between languages.

Real-World Applications

Convex Hull 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 Convex Hull helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Convex Hull 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 Convex Hull 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 Convex Hull 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 Convex Hull?

TypeScript adds no runtime, so the machinery is the same Array.prototype.sort with push and pop. What it adds is shape: type Point = readonly [x: number, y: number], a labelled tuple, or a readonly { x: number; y: number } interface, so the compiler stops you handing in a number[] of unknown length. On DefinitelyTyped, @types/d3-polygon declares polygonHull as taking an array of [number, number] pairs and returning that array type or null. The | null is what makes the typed binding worth using: it forces the degenerate fewer-than-three case to be handled at compile time.

What is the most common TypeScript mistake when implementing Convex Hull?

Types are erased, so the one place they cannot help is the boundary -- and this algorithm lives at one. JSON.parse returns any, so const pts = JSON.parse(body) as Point[] type-checks perfectly while handing you objects, strings, or two-element arrays that are actually one element long. A missing second slot makes p[1] undefined, the cross product becomes NaN, and NaN in a comparator is the worst possible value: it is neither negative, zero nor positive, so sort produces an arbitrary permutation instead of throwing. The hull comes out wrong with no stack trace anywhere in it. Validate at the edge with zod or a hand-written type guard; as is not validation.

How does Convex Hull actually perform in TypeScript?

Types cost nothing at runtime, but the emit does. for (const p of seq) compiled against an ES5 target with downlevelIteration becomes a helper that allocates an iterator object per call; target ES2015 or later and the allocation disappears. Spreads such as [...pts].reverse() lower to __spreadArray under old targets, copying twice instead of once. const enum inlines but breaks under isolatedModules, so most codebases forbid it. Everything else -- hidden classes, comparator monomorphism, packed-array behaviour -- is V8's, and is identical to plain JavaScript. 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

If you are a student, see what GitHub Copilot offers students for free 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.