> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Erect the Fence Python Solution with Tests

> Tested Python solution for LeetCode 587 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 587, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Math](/catalog/topics/math), [Geometry](/catalog/topics/geometry). [View on LeetCode](https://leetcode.com/problems/erect-the-fence/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 587   # by problem number
lcpy gen -s erect_the_fence   # by problem name
```

## Problem

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**.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect2-plane.jpg)

```
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 is inside the fence.
```

![Example 2](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0500-0599/0587.Erect%20the%20Fence/images/erect1-plane.jpg)

```
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 <= 3000`
* `trees[i].length == 2`
* `0 <= xi, yi <= 100`
* All the given positions are **unique**.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/erect_the_fence/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/erect_the_fence/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log n)
    # Space: O(n)
    def outer_trees(self, trees: list[list[int]]) -> list[list[int]]:
        points = sorted(tuple(p) for p in trees)

        def cross(i: int, j: int, k: int) -> int:
            a, b, c = points[i], points[j], points[k]
            return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])

        n = len(points)
        if n < 4:
            return [list(p) for p in points]

        visited = [False] * n
        stack = [0]
        for i in range(1, n):
            while len(stack) > 1 and cross(stack[-2], stack[-1], i) < 0:
                visited[stack.pop()] = False
            visited[i] = True
            stack.append(i)

        lower_hull_size = len(stack)
        for i in range(n - 2, -1, -1):
            if visited[i]:
                continue
            while len(stack) > lower_hull_size and cross(stack[-2], stack[-1], i) < 0:
                stack.pop()
            stack.append(i)

        stack.pop()
        return [list(points[i]) for i in stack]
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.