Convex hull: wrap the points
Stretch a rubber band around a set of points. Which points hold it in place? Build the outer boundary with two passes and a three-point turn test.
Video walkthrough
A rubber band around the points
Imagine pins on a board. Stretch a rubber band around all of them and let it tighten. It touches the extreme pins and encloses the rest. The convex hull is the smallest convex set containing the points. Convex means that the segment between any two points of the set stays inside the set.
With at least three non-collinear points, the result is a polygon. Interior points do not need to be vertices. One point gives a point; two points or a collinear set give a segment. A hull describes the outer envelope: it does not follow inward dents or reconstruct a detailed object silhouette.
Three points decide a turn
For points a, b, c, compute cross(a,b,c) = (bx−ax)(cy−ay) − (by−ay)(cx−ax). With x to the right and y upward, a positive value means a left turn from a→b to b→c; a negative value means a right turn. Zero means the three points are collinear. The diagram uses this same upward y axis.
We keep left turns in both scans. If cross ≤ 0, remove b from the current chain and test the new last two points with c. The dashed triangle highlights the tested triple. Red marks a right turn or a straight line; a cross appears on the point removed from this chain. This is a chain operation, not deletion from the input.
Andrew’s algorithm: two chains
Sort the points by increasing x, breaking ties by increasing y. Visit them in that order to build the lower chain. Consider a point, remove the last chain point while it makes a non-left turn, then append the candidate. Run the same procedure in reverse order for the upper chain. Concatenate the chains, omitting the last point of each so that their shared endpoints appear once.
In the nine-point example the sorted order starts A=(12,20), G=(16,48), B=(30,10). For A→G→B, cross = −544. G is removed from the lower chain. It still belongs to the upper chain in the final hull. The finished vertex order is counterclockwise and starts at the lexicographically smallest point; the first vertex is not repeated at the end.
What remains true after each insertion
After each push, the current stack is a convex chain for the processed prefix: every consecutive triple turns strictly left, and all points already scanned lie on or to the left of every directed chain edge. Popping the last point repairs a violated turn before the new candidate is appended. Lexicographic order lets us repair only the end of the chain.
The forward and reverse scans provide the two outer sides. A point removed in one scan can survive in the other. Intermediate chains are partial construction states; they need not enclose all input points. The final hull does enclose them, including points on its boundary.
What to try
Start with Nine points and step to the first turn test. Follow the triple A→G→B, then compare the two completed chains. Switch to Points on edges: the middle points of straight sides are omitted from the vertex list. On one line returns only the two extreme endpoints; Triangle and centre leaves the centre inside.
Move an interior point around inside the hull, then drag it outside. The outer boundary changes when needed. Editing always leaves the completed hull visible; Restart opens the steps for the edited input. Add points with the coordinate editor, or enable empty-space clicks. The editor also provides keyboard access to selection, movement and removal. Share preserves the input, playback position and speed on a clean player page. Video export records the full construction from the start, without sound.
Collinearity and exact turn signs
This version returns only extreme vertices: cross ≤ 0 removes intermediate collinear points. Those points are still on the boundary even though they are absent from the vertex list. Duplicate coordinates after rounding are rejected. A failed edit keeps the last valid input and playback position.
The editor accepts 1–20 distinct points within x=0…100 and y=0…70, rounded to 0.1. Turn tests use integer ticks, ten per coordinate unit. Products and differences remain exact integers in this small range, so no epsilon is used. The displayed cross value divides the tick determinant by 100. For arbitrary floating-point coordinates or large ranges, robust geometric predicates require additional care. Labels follow input order, not sorted position; removing an input point relabels the remaining input.
Work, counters and stored history
Given sorting in O(n log n), Andrew’s algorithm takes O(n log n) time overall. Each point is pushed once in each scan and can be popped at most once per scan; the two scans take O(n) time and O(n) extra space. The JavaScript sample uses the built-in sort; its implementation determines sorting cost.
Turn tests counts determinant evaluations in the scans, not comparisons inside sorting. Pushes counts stack insertions; Removals counts stack pops, not distinct input points. For n≥2 there are 2n pushes. The one-point shortcut performs no scan operations. Building both chains is shown as separate steps, and joining does not increase those counters.
The visualization stores independent arrays in every snapshot to support backward steps, seeking and export. It has O(n) events with up to O(n) data in each, so stored history and its construction can cost O(n²). That is separate from the linear working memory of the hull algorithm. The 20-point limit keeps the scene and its history manageable.
Executable code matching the example
The function below validates and rounds the same input, uses integer turn tests and returns the same extreme vertices as the player. Coordinates in the returned points are converted back to the original units. It omits animation events, counters and drawing.
Show the executable model
function convexHull(raw) {
if (!Array.isArray(raw) || raw.length < 1 || raw.length > 20)
throw new Error("Use 1–20 points");
const input = raw.map(p => {
if (!p || typeof p.x !== "number" || typeof p.y !== "number" ||
!Number.isFinite(p.x + p.y) || p.x < 0 || p.x > 100 ||
p.y < 0 || p.y > 70) throw new Error("Coordinates");
return { x: Math.round(p.x * 10), y: Math.round(p.y * 10) };
});
if (new Set(input.map(p => p.x + ":" + p.y)).size !== input.length)
throw new Error("Duplicate point");
const points = input.sort((a, b) => a.x - b.x || a.y - b.y);
const cross = (a, b, c) =>
(b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
function scan(order) {
const chain = [];
for (const p of order) {
while (chain.length >= 2 &&
cross(chain[chain.length - 2], chain[chain.length - 1], p) <= 0)
chain.pop();
chain.push(p);
}
return chain;
}
const hull = points.length === 1 ? points :
[...scan(points).slice(0, -1), ...scan([...points].reverse()).slice(0, -1)];
return hull.map(p => ({ x: p.x / 10, y: p.y / 10 }));
}