ADVANCED TECHNIQUES / ALGORITHM BRIEF

Computational geometry

Computational geometry solves problems about points, lines, and shapes: orientation, intersections, areas, convex hulls, and distances.

AdvancedPhase 08 / Topic 7 of 7Mental modelComplexityEdge cases
01

Overview

Computational geometry solves problems about points, lines, and shapes: orientation, intersections, areas, convex hulls, and distances. Interview problems in this area mostly rely on a few robust primitives computed with integers, such as the cross product, rather than floating-point angles or slopes.

The cross product of vectors AB and AC tells you whether C is to the left of, to the right of, or on the line AB. From it you get polygon area (shoelace formula), convexity checks, and convex hulls (Andrew's monotone chain). Counting points on a line uses reduced slopes stored as integer pairs to avoid floating-point errors.

Wrapping a rubber band around nails

Hammer nails into a board at each point and stretch a rubber band around all of them. When released, the band snaps to the convex hull: the smallest convex shape containing every nail.

02

When to use it

  • Input is a list of points, rectangles, or segments.
  • Questions about collinearity, orientation, area, or enclosing shapes.
  • Distances and nearest points (k closest, closest pair).
  • Rectangle overlap and area of unions.
03

Problem patterns it solves

Orientation with cross product

Recognize it when: left or right turn, collinear, convex polygon.

  • 1232. Check If It Is a Straight Line
  • 469. Convex Polygon
  • 1037. Valid Boomerang
Convex hull

Recognize it when: the fence enclosing all trees or points.

  • 587. Erect the Fence
Slopes as reduced fractions

Recognize it when: maximum points on one line.

  • 149. Max Points on a Line
Rectangles

Recognize it when: overlap test, total area, perfect cover.

  • 836. Rectangle Overlap
  • 223. Rectangle Area
  • 391. Perfect Rectangle
  • 850. Rectangle Area II
Distances

Recognize it when: k closest points, minimum area rectangle, squares.

  • 973. K Closest Points to Origin
  • 939. Minimum Area Rectangle
  • 593. Valid Square
04

Where it is used in real software

Maps and GIS

Checking whether a GPS point is inside a delivery zone polygon (point-in-polygon) powers geofencing in ride-sharing and delivery apps.

Games and physics engines

Collision detection uses bounding boxes, segment intersection, and convex shapes (separating axis theorem).

Computer graphics and CAD

Polygon triangulation, clipping, and hull computation underpin rendering and design tools.

Robotics

Path planning around obstacles uses convex hulls and visibility graphs.

05

Key terms

Cross product
cross(O, A, B) = (A.x - O.x)(B.y - O.y) - (A.y - O.y)(B.x - O.x). Positive: counter-clockwise turn.
Collinear
Cross product is 0: the three points are on one line.
Shoelace formula
Polygon area = |sum of (x_i y_(i+1) - x_(i+1) y_i)| / 2.
Convex hull
Smallest convex polygon containing all points.
Squared distance
dx^2 + dy^2; compare squared values to avoid sqrt.
06

Andrew's monotone chain convex hull

  1. 1
    Sort points by x, then y

    O(n log n).

  2. 2
    Build the lower hull

    For each point, while the last two hull points and this point make a non-left turn (cross <= 0), pop. Then push.

  3. 3
    Build the upper hull

    Same procedure iterating points in reverse order.

  4. 4
    Concatenate

    Remove the last point of each chain (it repeats the first of the other).

  5. 5
    Collinear points

    Use cross < 0 instead of <= 0 to keep points on the hull edges when required.

07

Orientation tests with the cross product

O = (0, 0), A = (2, 0)

Step 1 / 3
Bcross(O, A, B)Meaning
(1, 1)2 x 1 - 0 x 1 = 2positive: B is left of O->A (counter-clockwise)
(1, -1)2 x (-1) - 0 x 1 = -2negative: B is right of O->A (clockwise)
(4, 0)2 x 0 - 0 x 4 = 0zero: collinear

NOWB: (1, 1) | cross(O, A, B): 2 x 1 - 0 x 1 = 2 | Meaning: positive: B is left of O->A (counter-clockwise)

One integer formula answers left, right, or on-the-line with no division or floating point. Every hull, convexity, and intersection algorithm below is built on it.

08

Implementation

const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); // Shoelace formulafunction polygonArea(points) {  let twice = 0;  for (let i = 0; i < points.length; i++) {    const [x1, y1] = points[i];    const [x2, y2] = points[(i + 1) % points.length];    twice += x1 * y2 - x2 * y1;  }  return Math.abs(twice) / 2;} // Monotone chain convex hull (drops collinear edge points)function convexHull(points) {  const pts = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);  if (pts.length <= 2) return pts;  const build = (list) => {    const hull = [];    for (const p of list) {      while (hull.length >= 2 && cross(hull.at(-2), hull.at(-1), p) <= 0) hull.pop();      hull.push(p);    }    hull.pop();    return hull;  };  return [...build(pts), ...build([...pts].reverse())];} // 149. Max Points on a Line: slopes as reduced integer pairsfunction maxPoints(points) {  const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));  let best = Math.min(points.length, 1);  for (let i = 0; i < points.length; i++) {    const slopes = new Map();    for (let j = i + 1; j < points.length; j++) {      let dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];      const g = gcd(dx, dy);      dx /= g; dy /= g;      if (dx < 0 || (dx === 0 && dy < 0)) { dx = -dx; dy = -dy; } // normalize sign      const key = dx + "/" + dy;      slopes.set(key, (slopes.get(key) ?? 1) + 1);      best = Math.max(best, slopes.get(key));    }  }  return best;}
09

Complexity and performance

Cross product / orientationO(1)

Integer arithmetic.

Convex hullO(n log n)

Sorting dominates.

Max points on a lineO(n^2)

Slopes from each anchor point.

Polygon areaO(n)

Shoelace formula.

10

Trade-offs

Integers vs floating point

Slopes and angles in floating point cause precision bugs (0.1 + 0.2). Cross products and reduced fractions stay exact with integers.

Overflow

Products of coordinates up to 10^4 fit in 32 bits, but 10^9 coordinates need 64-bit (long) arithmetic.

11

Variants and related techniques

Point in polygon

Ray casting counts edge crossings; odd means inside.

Closest pair of points

Divide and conquer in O(n log n).

Line sweep

Process events sorted by x to compute rectangle union areas or segment intersections.

12

Common mistakes

  • Using slope dy / dx as a float key.

    Fix: Use the reduced pair (dx / g, dy / g) with a normalized sign; vertical lines have dx = 0.

  • Comparing distances with sqrt.

    Fix: Compare squared distances to stay exact and faster.

  • Touching rectangles counted as overlapping.

    Fix: Overlap requires strictly positive width and height (use >, not >=).

13

Interview questions

How do you check if three points are collinear without division?

Compute the cross product of AB and AC. It is zero exactly when the points are collinear, and it uses only multiplication and subtraction.

Why sort by x before building a convex hull?

Monotone chain processes points left to right so each new point can only remove points from the end of the current chain, giving a stack-based O(n) pass after sorting.

14

Practice problems

ProblemDifficultyWhat it trains
1232. Check If It Is a Straight LineEasyCross product.
836. Rectangle OverlapEasyAxis overlap.
223. Rectangle AreaMediumInclusion-exclusion.
939. Minimum Area RectangleMediumDiagonal pairs in a set.
149. Max Points on a LineHardReduced slopes.
587. Erect the FenceHardConvex hull with collinear points.