You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.
Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed.
Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.
Example 1:
Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] Output: [[1,1],[2,0],[4,2],[3,3],[2,4]] Explanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence.
Example 2:
Input: trees = [[1,2],[2,2],[4,2]] Output: [[4,2],[2,2],[1,2]] Explanation: The fence forms a line that passes through all the trees.
Constraints:
1 <= trees.length <= 3000trees[i].length == 20 <= xi, yi <= 100The Monotone Chain Algorithm is an efficient algorithm for finding the convex hull of a set of 2D points. It constructs the hull in O(n log n) time. The idea is to sort the points, then construct the lower and upper hulls in O(n) time each. Points are rejected if they don't form a 'left turn', which can be determined using cross product.
This C code implements the Monotone Chain Algorithm for finding the convex hull. First, it sorts the points, then constructs the lower and upper hulls. Sorting ensures all points are processed in order, while stack logic applies to maintaining valid hull points by checking the turn direction using cross product.
C++
Java
Python
C#
JavaScript
Time complexity is O(n log n) due to sorting. Space complexity is O(n) for storing the hull points.
The Gift Wrapping Algorithm, also known as Jarvis March, is another method to find the convex hull. It builds the hull one vertex at a time, looking for the line tangent to the current edge and a point in the set of all remaining points. It's less efficient than Monotone Chain, operating in O(nh) time complexity, where h is the number of hull vertices.
This C implementation of the Gift Wrapping Algorithm iteratively chooses the most counterclockwise point until it returns to the start point. It determines orientation by calculating the cross product and compares relative angles.
C++
Java
Python
C#
JavaScript
Time complexity is O(nh) where n is the number of points and h is the number of points on the hull. Space complexity is O(h) for the hull array.
| Approach | Complexity |
|---|---|
| Monotone Chain Algorithm (Convex Hull) | Time complexity is O(n log n) due to sorting. Space complexity is O(n) for storing the hull points. |
| Gift Wrapping Algorithm (Jarvis March) | Time complexity is O(nh) where n is the number of points and h is the number of points on the hull. Space complexity is O(h) for the hull array. |
Erect the Fence -(GOOGLE) : Explanation ➕ Live Coding • codestorywithMIK • 5,213 views views
Watch 9 more video solutions →Practice Erect the Fence with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor