Convex hull
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The convex hull of a set of points is the tightest outline that wraps all of them, like a rubber band around nails. It lets you ignore every point inside and work with only the few on the outside.
Practical use cases
- Web app: Delivery zone boundary on a map. A food-delivery admin wants to draw the area covering all customer addresses. Instead of plotting 50,000 dots, the app finds the outer points and draws one polygon. The map stays smooth because only about 40 outline points are drawn.
- Web app: Map markers and zoom-to-fit. A store locator shows thousands of matching shops and shades the region they cover. Only the outer shops are joined into one polygon, so the browser draws a few points instead of thousands, and users see at a glance where the results are.
- Web app: Image and shape recognition in an upload tool. A photo tool that detects a hand or a logo in an uploaded image takes the hull of the detected pixels to measure its width, height and outline quickly, so users see feedback straight after uploading.
- System: Collision detection in games and GIS. Game engines wrap objects in hulls to test collisions cheaply, and GIS tools use hulls to outline clusters of data. The inside points never need checking, so a short outline replaces a cloud of thousands of points.
The story: The Rubber Band Around the Nails
Kabir's science teacher hammered seven nails into a wooden board and gave him a big rubber band. "Stretch it around all the nails and let go. Tell me which nails the band touches."
Kabir tried every combination of nails and checked whether the band hugged the rest. It took him till lunch. His sister Mira laughed. "Just walk around the edge. At each nail, if you have to turn left, keep it. If you have to turn right, the nail is hiding inside, so skip it."
She sorted the nails from left to right and built the bottom of the band: add a nail, and if the last turn goes the wrong way, drop the previous nail and test again. Then she repeated it coming back from the right to build the top.
The shape the rubber band makes is the convex hull, and walking around it with a "which way do I turn?" check is a famous way to build it.
How to spot this problem, and where you need it
You have many points and only the outermost ones matter, for drawing a boundary, a fence, a service area or a quick shape check.
Signs you need it
- The task says "smallest polygon containing all points", "outer boundary", "fence" or "farthest pair".
- You are drawing or testing against thousands of points when only the edge ones change the result.
- A bounding rectangle is too rough, and you need a snug outline.
Where to use it in a project
- Map features showing service zones, coverage areas or the region covered by search results.
- Game or animation collision tests that use simple shape outlines around objects.
- Image analysis that measures an object's outline after detection in an uploaded picture.
The solution
Sort the points left to right. Build the lower edge by adding points one at a time and removing the previous point whenever the last three make a clockwise turn (an inward dent). Then build the upper edge the same way from the other direction. Join both edges, and the points left form the hull, in order around the outline.
Payoff: Before: 50,000 points drawn and tested. After: maybe 40 outline points that describe the same area.
Explain it like I am 8
Put your hands around a bunch of pencils standing on the table and squeeze with a rubber band. Only the outermost pencils touch it. Everything in the middle is just surrounded. Finding those outer pencils is the convex hull.
How it works, step by step
- Sort the points from left to right (break ties by height).
- Bottom pass: go left to right with a stack of points. Before adding a point, while the last two on the stack and the new one do not turn left, pop the top.
- Top pass: do the same going right to left to build the top edge.
- Join the two passes, leaving out the last point of each so the corners are not counted twice.
- The turn test is a tiny function (the "cross product") that says: left, right or straight. The rest is just a stack.
The code in four languages
PHP
<?php
// The "turn test": positive = left turn, negative = right turn, 0 = straight line.
function cross(array $o, array $a, array $b): int {
return ($a[0] - $o[0]) * ($b[1] - $o[1]) - ($a[1] - $o[1]) * ($b[0] - $o[0]);
}
// Build one side of the hull (bottom if given left-to-right, top if right-to-left).
function buildSide(array $points): array {
$stack = [];
foreach ($points as $p) {
// while the last two points and the new one do not turn left, drop the last one
while (count($stack) >= 2 && cross($stack[count($stack) - 2], $stack[count($stack) - 1], $p) <= 0) {
array_pop($stack);
}
$stack[] = $p;
}
return $stack;
}
function convexHull(array $pts): array {
sort($pts); // by x, then by y
if (count($pts) < 3) return $pts;
$lower = buildSide($pts);
$upper = buildSide(array_reverse($pts));
array_pop($lower); // last point of each side is the first of the other
array_pop($upper);
return array_merge($lower, $upper);
}
$nails = [[1, 3], [2, 6], [3, 1], [4, 4], [5, 1], [6, 5], [7, 3]];
$hull = convexHull($nails);
echo implode(' ', array_map(fn($p) => '(' . $p[0] . ',' . $p[1] . ')', $hull)), "\n";
// (1,3) (3,1) (5,1) (7,3) (6,5) (2,6) - nail (4,4) is insideJavaScript
// The "turn test": positive = left turn, negative = right turn, 0 = straight line.
function cross(o, a, b) {
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
}
// Build one side of the hull (bottom if given left-to-right, top if right-to-left).
function buildSide(points) {
const stack = [];
for (const p of points) {
// while the last two points and the new one do not turn left, drop the last one
while (stack.length >= 2 && cross(stack[stack.length - 2], stack[stack.length - 1], p) <= 0) {
stack.pop();
}
stack.push(p);
}
return stack;
}
function convexHull(points) {
const pts = points.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]); // by x, then by y
if (pts.length < 3) return pts;
const lower = buildSide(pts);
const upper = buildSide(pts.slice().reverse());
lower.pop(); // last point of each side is the first of the other
upper.pop();
return lower.concat(upper);
}
const nails = [[1, 3], [2, 6], [3, 1], [4, 4], [5, 1], [6, 5], [7, 3]];
const hull = convexHull(nails);
console.log(hull.map(p => '(' + p[0] + ',' + p[1] + ')').join(' '));
// (1,3) (3,1) (5,1) (7,3) (6,5) (2,6) - nail (4,4) is insideJava
import java.util.*;
public class Main {
// The "turn test": positive = left turn, negative = right turn, 0 = straight line.
static int cross(int[] o, int[] a, int[] b) {
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
}
// Build one side of the hull (bottom if given left-to-right, top if right-to-left).
static List<int[]> buildSide(List<int[]> points) {
List<int[]> stack = new ArrayList<>();
for (int[] p : points) {
// while the last two points and the new one do not turn left, drop the last one
while (stack.size() >= 2
&& cross(stack.get(stack.size() - 2), stack.get(stack.size() - 1), p) <= 0) {
stack.remove(stack.size() - 1);
}
stack.add(p);
}
return stack;
}
static List<int[]> convexHull(List<int[]> points) {
List<int[]> pts = new ArrayList<>(points);
pts.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); // by x, then by y
if (pts.size() < 3) return pts;
List<int[]> lower = buildSide(pts);
List<int[]> reversed = new ArrayList<>(pts);
Collections.reverse(reversed);
List<int[]> upper = buildSide(reversed);
lower.remove(lower.size() - 1); // last point of each side is the first of the other
upper.remove(upper.size() - 1);
lower.addAll(upper);
return lower;
}
public static void main(String[] args) {
List<int[]> nails = List.of(new int[]{1, 3}, new int[]{2, 6}, new int[]{3, 1}, new int[]{4, 4},
new int[]{5, 1}, new int[]{6, 5}, new int[]{7, 3});
List<int[]> hull = convexHull(nails);
StringBuilder sb = new StringBuilder();
for (int[] p : hull) {
if (sb.length() > 0) sb.append(' ');
sb.append('(').append(p[0]).append(',').append(p[1]).append(')');
}
System.out.println(sb);
// (1,3) (3,1) (5,1) (7,3) (6,5) (2,6) - nail (4,4) is inside
}
}Go
package main
import (
"fmt"
"slices"
"strings"
)
type Point struct{ x, y int }
// cross is the "turn test": positive = left turn, negative = right turn, 0 = straight line.
func cross(o, a, b Point) int {
return (a.x-o.x)*(b.y-o.y) - (a.y-o.y)*(b.x-o.x)
}
// buildSide builds one side of the hull (bottom if given left-to-right, top if right-to-left).
func buildSide(points []Point) []Point {
var stack []Point
for _, p := range points {
// while the last two points and the new one do not turn left, drop the last one
for len(stack) >= 2 && cross(stack[len(stack)-2], stack[len(stack)-1], p) <= 0 {
stack = stack[:len(stack)-1]
}
stack = append(stack, p)
}
return stack
}
func convexHull(points []Point) []Point {
pts := slices.Clone(points)
slices.SortFunc(pts, func(a, b Point) int { // by x, then by y
if a.x != b.x {
return a.x - b.x
}
return a.y - b.y
})
if len(pts) < 3 {
return pts
}
lower := buildSide(pts)
reversed := slices.Clone(pts)
slices.Reverse(reversed)
upper := buildSide(reversed)
lower = lower[:len(lower)-1] // last point of each side is the first of the other
upper = upper[:len(upper)-1]
return append(lower, upper...)
}
func main() {
nails := []Point{{1, 3}, {2, 6}, {3, 1}, {4, 4}, {5, 1}, {6, 5}, {7, 3}}
hull := convexHull(nails)
parts := make([]string, len(hull))
for i, p := range hull {
parts[i] = fmt.Sprintf("(%d,%d)", p.x, p.y)
}
fmt.Println(strings.Join(parts, " "))
// (1,3) (3,1) (5,1) (7,3) (6,5) (2,6) - nail (4,4) is inside
}Time: O(n log n) · Extra space: O(n). Sorting costs n log n; each point is pushed and popped at most once per pass.
Watch out for
- Popping only when the turn is strictly right. Use "not strictly left" (
<= 0) so points on a straight edge are dropped. - Mixing up the y-direction: on a screen y grows downward, which flips left and right. Decide your convention and keep it.
- Forgetting to remove the duplicate end point of each pass, so corners appear twice.
Quick check
- In the bottom pass, when do we pop the top of the stack?
- When the new point does not make a left turn
- When the new point is the biggest
- Never
- What is the first step of this method?
- Draw the hull
- Sort the points left to right
- Count the points
- Why is the total work O(n log n)?
- Every pair is compared
- The stack is sorted each time
- Sorting dominates; the stack passes are linear