You are given the positions of trees in a garden, trees[i] = [x, y]. A fence will be a single loop of rope pulled as tight as possible around all of them: every tree must end up inside the loop or on it.
Return the trees that the tight fence touches, meaning every tree that lies on the fence line, including trees in the middle of a straight stretch. The order does not matter.
Example 1
Input: trees = [[1,1], [4,0], [0,2], [2,0], [4,2], [0,0]] Output: [[0,0], [2,0], [4,0], [4,2], [0,2]] Why: the fence is the 4 × 2 rectangle; (2,0) sits on its bottom side, (1,1) is inside
2 more examples and the constraints
Example 2
Input: trees = [[3,1], [3,6], [3,4]] Output: [[3,1], [3,4], [3,6]] Why: the trees are in a line, so the fence runs along all of them
Example 3
Input: trees = [[7,7]] Output: [[7,7]] Why: one tree is its own fence
Constraints
- 1 ≤ number of trees ≤ 3,000
- 0 ≤ x, y ≤ 100
- No two trees share a position
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every lineO(n³)
- Monotone chainO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 3,000 trees | Verdict |
|---|---|---|---|
| Check every line | O(n³) | Easy to reason about; too slow | |
| Monotone chain | O(n log n) | Best; sort, then two stack passes |
n = number of trees.
Edge cases to test
- One or two trees. They are all on the fence; return them as they are.
- All trees in a line. Every tree is on the fence. The two halves both hold all of them, so remove duplicates.
- Trees on a straight side. (2,0) between (0,0) and (4,0) has cross product 0 and must be kept.
- Vertical sides. Sorting by x and then y keeps trees with equal x in order, so a vertical side is walked correctly.
- Trees inside. A tree strictly inside, like (1,1), is popped and never returned.
Common mistakes
- Popping on cross ≤ 0, which drops trees in the middle of a straight side.
- Returning the joined halves without removing the shared trees, or every tree twice when all are in a line.
- Getting the sign of the cross product backwards, which builds the fence around the wrong side.
How to talk through it
- 1Clarify. Do trees on a straight side count? Can all trees be in a line? Is any order fine?
- 2Give the brute force. A pair is a fence line when every tree is on one side; O(n³).
- 3Name the pattern. This is the convex hull. Monotone chain: sort, then a stack per half.
- 4Explain the turn test. Cross product below 0 is a clockwise turn, so the middle tree is inside; 0 means a straight stretch, keep it.
- 5Test out loud. Run a line of trees, a single tree and a rectangle with a tree on one side before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?