#587

Erect the Fence

Hard
ArrayMathGeometryConvex HullSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses the Convex Hull algorithm, which efficiently finds the smallest enclosing polygon for a set of points. This method significantly reduces the number of points we need to consider for the fence.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the trees based on their x-coordinates (and y-coordinates for ties).
  2. 2Step 2: Build the lower hull by iterating through the sorted points and maintaining a stack of points that form the hull.
  3. 3Step 3: Build the upper hull by iterating through the sorted points in reverse order.
  4. 4Step 4: Combine the lower and upper hulls to get the complete fence.
solution.py21 lines
1# Full working Python code
2from typing import List
3
4def optimal_fence(trees: List[List[int]]) -> List[List[int]]:
5    def cross(o, a, b):
6        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
7
8    trees = sorted(trees)
9    lower = []
10    for p in trees:
11        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0:
12            lower.pop()
13        lower.append(p)
14
15    upper = []
16    for p in reversed(trees):
17        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0:
18            upper.pop()
19        upper.append(p)
20
21    return lower[:-1] + upper[:-1]

Complexity note: The time complexity is dominated by the sorting step, which is O(n log n), while the space complexity is O(n) due to the storage of the hull points.

  • 1Understanding the Convex Hull is crucial for solving perimeter problems efficiently.
  • 2Sorting points is often a necessary step in geometric algorithms.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.