06. Erect the Fence (Convex Hull Graham Scan)
Given an array trees where trees[i] = [x, y] represents the location of a tree in the garden, return the coordinates of trees that are located on the perimeter of the fence enclosing all trees (Convex Hull).
How It Works & Algorithmic Design
Solves using Andrew's Monotone Chain Convex Hull Algorithm:
- Sort: Sort points primarily by x-coordinate, secondarily by y-coordinate.
- Cross Product Helper:
cross(p1, p2, p3)determines orientation of turns. - Build Upper & Lower Hulls:
- Loop through sorted points and construct lower hull using stack.
- Pop points from stack while cross product indicates non-left turn (
cross < 0). - Repeat procedure in reverse to construct upper hull.
- Combine & Deduplicate: Merge lower and upper hull sets.
Why This Approach Works Best
Monotone chain processes geometric points cleanly in $O(n \log n)$ time.
Example Walkthrough
[[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
2D trees points.
Outer points enclosing all internal trees.
Fence boundary.
[[1,1],[2,0],[4,2],[3,3],[2,4]]
Hull boundary points.
Answer: Erect the Fence Monotone Chain implementation
function outerTrees(trees) {
trees.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
function cross(p1, p2, p3) {
return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0]);
}
const lower = [], upper = [];
for (const p of trees) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) < 0) {
lower.pop();
}
lower.push(p);
}
for (let i = trees.length - 1; i >= 0; i--) {
const p = trees[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) < 0) {
upper.pop();
}
upper.push(p);
}
const set = new Set();
const res = [];
for (const p of [...lower, ...upper]) {
const key = `${p[0]},${p[1]}`;
if (!set.has(key)) {
set.add(key);
res.push(p);
}
}
return res;
}Construct upper and lower convex hulls by sorting points and checking cross-product orientation.
Cross product sign determines left vs right geometric turns.
Monotone chain constructs lower and upper perimeter hulls independently.
Time complexity $O(n \log n)$ due to initial point sorting.