Erect the Fence - Problem

You are tasked with fencing a garden containing various trees using the minimum length of rope possible. Given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden, you need to find the convex hull - the smallest perimeter that encloses all trees.

The fence should form a convex polygon that contains or touches every tree. Trees that lie exactly on the fence perimeter are part of the solution.

Goal: Return the coordinates of all trees that are located exactly on the fence perimeter.

Input: Array of 2D coordinates representing tree positions

Output: Array of coordinates that form the convex hull boundary

Note: You may return the coordinates in any order.

Input & Output

example_1.py — Basic Square Garden
$ Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
Output: [[1,1],[2,0],[3,3],[4,2],[2,4]]
💡 Note: The fence forms a pentagon that encloses all trees. The points [1,1], [2,0], [4,2], [3,3], and [2,4] form the convex hull boundary.
example_2.py — Collinear Points
$ Input: trees = [[1,2],[2,2],[4,2]]
Output: [[4,2],[2,2],[1,2]]
💡 Note: All three points lie on the same horizontal line, so they all must be included in the fence perimeter since they form the convex hull.
example_3.py — Single Point
$ Input: trees = [[0,0]]
Output: [[0,0]]
💡 Note: With only one tree, the fence is just that single point - trivial convex hull case.

Constraints

  • 1 ≤ trees.length ≤ 3000
  • trees[i].length == 2
  • 0 ≤ xi, yi ≤ 100
  • All the given positions are unique.

Visualization

Tap to expand
Erect the Fence - Convex Hull Problem INPUT 0 1 2 3 4 (1,1) (2,2) (2,0) (2,4) (3,3) (4,2) trees array: [[1,1],[2,2],[2,0], [2,4],[3,3],[4,2]] 6 trees in garden Find fence boundary ALGORITHM STEPS 1 Find Leftmost Point Start from (1,1) - lowest x 2 Gift Wrapping Find next CCW point 3 Cross Product Test Check turn direction 4 Include Collinear Add points on boundary Wrapping Process: Red = Hull | Gray = Interior FINAL RESULT (1,1) (2,0) (2,4) (3,3) (4,2) (2,2) Output: [[1,1],[2,0],[3,3], [4,2],[2,4]] OK - 5 boundary points (2,2) is interior - excluded Time: O(n*h) | Space: O(n) Key Insight: The convex hull includes all points that form the outer boundary. Use cross product to determine turn direction: positive = left turn (CCW), negative = right turn (CW), zero = collinear. Gift Wrapping (Jarvis March) wraps around points like wrapping a string around pegs. TutorialsPoint - Erect the Fence | Optimal Solution (Gift Wrapping / Jarvis March) Convex Hull Algorithm - O(n*h) time complexity where h = hull points
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 22
24.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen