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 VisualizationStart PointAlgorithm Steps:1. Find bottom-most tree2. Sort by polar angle3. Build hull with stack4. Include boundary pointsTrees to fenceFence posts (hull)๐ŸŽฏ The fence uses minimum rope while enclosing all trees - this is the convex hull!
Understanding the Visualization
1
Identify Start Point
Find the bottom-most point (lowest y-coordinate, leftmost if tie) as our anchor point
2
Sort by Polar Angle
Sort all other points by the angle they make with the start point, creating a radial sweep
3
Graham Scan
Process points in order, using a stack to maintain only the convex boundary points
4
Handle Collinear Points
Include all points that lie exactly on the boundary edges of the convex hull
Key Takeaway
๐ŸŽฏ Key Insight: The convex hull is like a rubber band stretched around all points - Graham's scan efficiently finds this boundary using polar angle sorting and cross products to detect turns.
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