Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Geometry

Wrapping the Points.

Stretch a rubber band around a scatter of points and let it snap tight — the polygon it forms is the convex hull. Andrew’s monotone chain computes it without any rubber band: sort the points left to right, then sweep once to build the lower boundary and once to build the upper, and at each step throw away any point that would make the boundary turn the wrong way. A single cross product decides every turn. Step through the two sweeps and watch the hull tighten.

O(n log n) time (the sort) · O(n) hull build · the cross product decides every turn
convex hull

The smallest convex polygon that contains every point — the rubber-band boundary.

cross product

cross(O,A,B): positive = left turn, negative = right turn, zero = collinear.

lower / upper chain

Build the bottom boundary left-to-right, then the top boundary right-to-left.

pop

Remove the last hull point whenever adding the new point makes a non-left turn.

hull.js — sort, sweep, pop the wrong turns
Ready
Points sorted left to right. We sweep building the lower chain: add each point, and while the last three make a non-left turn, pop the middle one. Then repeat for the upper chain. Step to advance.
lower
chain
0
hull points
–
last action

How it works

Every decision reduces to the sign of one cross product. For the last two points on the current chain, O and A, and the incoming point B, the value cross(O, A, B) is positive when O→A→B turns left (counter-clockwise) and negative when it turns right. A convex boundary only ever turns one way, so any point that produces the wrong sign can’t be on the hull — pop it. Doing this left-to-right builds the lower boundary; doing it right-to-left builds the upper. Joined, they wrap every point.

1

Sort points left to right

Order all points by x (ties by y). This sorting step is the O(n log n) cost; everything after is linear.

2

Sweep the lower chain

Add points one by one. While the last two hull edges make a non-left turn (cross ≤ 0), pop the middle point — it dents inward and can’t be on the hull.

3

Sweep the upper chain

Repeat right-to-left to build the top boundary with the same pop rule. The lower chain traces the bottom, the upper traces the top.

✓

Join the two chains

Concatenate the lower and upper chains (dropping the shared endpoints) to get the full convex hull — the tightest convex polygon enclosing all the points.

Time
O(n log n)
Hull build
O(n)
Decision
cross product
Output
convex polygon

The code

# Andrew's monotone chain — O(n log n) def convex_hull(pts): pts = sorted(set(pts)) # by x, then y def cross(o, a, b): return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0]) def half(points): chain = [] for p in points: while len(chain) >= 2 and cross(chain[-2], chain[-1], p) <= 0: chain.pop() # non-left turn -> drop it chain.append(p) return chain[:-1] return half(pts) + half(pts[::-1]) # lower + upper

Quick check

1. What does the cross product cross(O, A, B) tell you?

2. Why does the monotone chain build two separate chains?

3. What dominates the running time?

FAQ

What is a convex hull?

The smallest convex polygon containing all the points — the shape a rubber band stretched around the outermost points would form. Every point lies inside or on it, and it never bends inward.

How does Andrew’s monotone chain work?

It sorts points by x, then sweeps left-to-right for the lower boundary and right-to-left for the upper. Each step adds a point and, while the last three make a non-left turn (cross-product test), pops the middle one. Joining the chains gives the hull in O(n log n).

How is it different from the gift-wrapping (Jarvis march) algorithm?

Gift wrapping (Jarvis march) picks each hull point by scanning all points — O(nh), fast for a small hull, slow for a large one. Monotone chain (and Graham scan) is always O(n log n) regardless of hull size — usually the better general-purpose choice.

What are convex hulls used for?

Collision detection and physics engines, bounding shapes in graphics and GIS, pathfinding around obstacles, shape analysis and clustering, and as a primitive for other geometry algorithms (point-set diameter, smallest enclosing shapes).

The picture: the rubber band

0123456coordinates: x 0 to 4, y 0 to 3solid: hull (P0 P3 P6 P5 P2)dashed: popped (P1, P4)
The seven points of the worked example, numbered in sorted order (left to right). The outline is the hull the algorithm returns; the dashed points, P1 and P4, were pushed onto a chain at some point and later popped because a later point showed they were dents.

Worked example, step by step

Take the points [(2,0), (0,1), (1,1), (3,2), (1,3), (4,0), (2,2)]. Sorted by x, then y, they become P0 to P6 as in the picture. The table runs the lower chain left to right and the upper chain right to left. “Cross” is the turn made by the last two stack points and the new point; zero or negative means a right turn or a straight line, so the middle point is popped.

#ChainPoint(s) addedCross values testedActionStack after
1lowerP0 (0, 1), P1 (1, 1)-push both (no turn to test yet)[P0, P1]
2lowerP2 (1, 3)2push[P0, P1, P2]
3lowerP3 (2, 0)-2, -1pop P2, pop P1, push[P0, P3]
4lowerP4 (2, 2)4push[P0, P3, P4]
5lowerP5 (3, 2)-2, 5pop P4, push[P0, P3, P5]
6lowerP6 (4, 0)-4, 2pop P5, push[P0, P3, P6]
7upperP6 (4, 0), P5 (3, 2)-push both (no turn to test yet)[P6, P5]
8upperP4 (2, 2)2push[P6, P5, P4]
9upperP3 (2, 0)2push[P6, P5, P4, P3]
10upperP2 (1, 3)-2, -1, 3pop P3, pop P4, push[P6, P5, P2]
11upperP1 (1, 1)4push[P6, P5, P2, P1]
12upperP0 (0, 1)-2, 5pop P1, push[P6, P5, P2, P0]

The two pops at step 3 are the instructive ones: P2 at (1, 3) and P1 at (1, 1) were both on the stack, and P3 at (2, 0) arrived below them. It made a right turn at each, so both were popped, and P3 became the next lower-hull vertex after P0. Likewise, step 10 removes P3 and P4 from the upper chain when P2 arrives. Step 11 pushes P1 on the way back, and step 12 pops it again as soon as P0 shows it is inside. Each chain is a stack where every point is pushed once and popped at most once, which is why the passes are linear. Joining lower [P0, P3, P6] and upper [P6, P5, P2, P0], after dropping each chain's last point (the shared endpoints), gives the hull P0, P3, P6, P5, P2: five of the seven points.

Complexity and trade-offs

CaseTimeSpaceWhy
Monotone chain (Andrew)O(n log n)O(n)The sort dominates; the two chain passes are O(n) because each point is pushed and popped at most once.
Gift wrapping (Jarvis march)O(n · h)O(h)Scans all n points for each of the h hull vertices. Better when h is tiny, worse when most points are on the hull.
Graham scanO(n log n)O(n)Sorts by angle around a low point instead of by x; the same bound with more care over ties.
Divide and conquer (merge hulls)O(n log n)O(n)Splits by x, builds two hulls and joins them; useful when the data is split across machines.
Chan’s algorithmO(n log h)O(n)Output-sensitive: combines small hulls with gift wrapping, beating the sort when h is small.

Where h matters, the counts are stark. On 10,000 pseudo-random points in a square, the hull had 25 vertices; the monotone chain made 39,969 cross-product tests after sorting, while gift wrapping made 249,975. On 2,000 points of the form (i, i²), every point is a hull vertex: the chain made 3,996 tests, gift wrapping 3,998,000. The trade-off is that the sort is a floor of Ω(n log n) in the standard models of computation, so the chain's cost cannot be improved except by output-sensitive methods such as Chan's, and gift wrapping only wins when you know the hull is small. The cross product also needs exact arithmetic: with integer coordinates it is exact, but floats can misjudge a nearly straight turn.

Common mistakes

  • Popping only on strictly negative cross

    With cross < 0 instead of <= 0, a point lying exactly on an edge survives. For [(0,0), (2,0), (2,2), (0,2), (1,0)] the buggy version returns 5 vertices; the correct hull of the square has 4. The equals case is what removes collinear points.

  • Not dropping each chain’s last point

    The lower chain ends where the upper begins, and vice versa. Concatenating the full chains repeats both extreme points: for the example above that gives 7 entries instead of 5.

  • Sorting by x alone

    When several points share an x, they must be ordered by y as well. Sorting [(2,1), (2,2), (2,0), (0,1)] by x only keeps the input order within the tie and yields [(0,1), (2,0), (2,1)], which drops the vertex (2, 2). The correct hull is [(0,1), (2,0), (2,2)].

  • Overflowing the cross product

    The cross product multiplies two coordinate differences. With 32-bit integers and coordinates around 10⁵ the product overflows: 100000 × 30000 is 3,000,000,000 but wraps to -1294967296, flipping a left turn into a right turn and popping a real hull vertex. Use 64-bit integers, or compare with care.

  • No guard for tiny inputs

    With a single point, the lower and upper chains each hold that point, and removing each chain's last element leaves [] (an empty hull). Return the sorted unique points directly when there are two or fewer.

Where this shows up

  • Collision detection

    Wrapping an object in the convex hull of its vertices gives a simple shape for which overlap tests are fast, and many physics engines use convex shapes for exactly this reason.

  • Computational geometry building blocks

    The diameter of a point set (its farthest pair) is found among hull vertices, and rotating calipers walks around the hull to get it in linear time after the hull is built.

  • Outlier and boundary detection

    Peeling hulls layer by layer ranks points by depth, a classic non-parametric way to find the outermost observations in a two-dimensional dataset.

  • Maps and imagery

    Drawing a tight boundary around a cluster of locations, or bounding the shape of a detected object in an image, is a hull of the relevant points.

SOLVE IT YOURSELF

Solve it: stretch a rubber band around the points

Sort the points, walk left to right building the bottom edge, then right to left for the top — popping any point that turns the wrong way. Andrew’s monotone chain, in about fifteen lines. Python or TypeScript.

YOUR TASK

Implement convex_hull(points): return the hull as a list of (x, y) points in counter-clockwise order, starting from the lexicographically smallest. Points strictly inside the hull, and points lying on an edge, must both be excluded.

HINTS — 6 IDEAS
  1. Sort the points lexicographically and drop duplicates. Everything downstream assumes that order.
  2. The cross product (a−o) × (b−o) is the whole engine: positive means a left turn, negative a right turn, zero means collinear.
  3. Build the lower hull left to right: before pushing a point, pop while the last two plus the new one do not make a left turn.
  4. Build the upper hull by doing exactly the same walk over the reversed list.
  5. Use <= 0 in the pop test, not < 0. The equals case is what discards points sitting exactly on an edge — with < they survive into the output.
  6. Concatenate, dropping the last point of each half — those are the shared endpoints and would otherwise appear twice.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextLine Sweep: Sliding the Line Next on the “Points, lines and giving up” ladder · rung 2 of 3

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms