Erect the Fence II - Problem

You are given a 2D integer array trees where trees[i] = [xi, yi] represents the location of the ith tree in the garden.

You are asked to fence the entire garden using the minimum length of rope possible. The garden is well-fenced only if all the trees are enclosed and the rope used forms a perfect circle.

A tree is considered enclosed if it is inside or on the border of the circle.

More formally, you must form a circle using the rope with a center (x, y) and radius r where all trees lie inside or on the circle and r is minimum.

Return the center and radius of the circle as a length 3 array [x, y, r]. Answers within 10⁻⁵ of the actual answer will be accepted.

Input & Output

Example 1 — Square Formation
$ Input: trees = [[1,1],[2,2],[2,0],[0,2]]
Output: [1.0,1.0,1.414213]
💡 Note: The smallest circle that encloses all four trees has center at (1,1) with radius approximately √2 ≈ 1.414213. This circle passes through points (2,2), (2,0), and (0,2).
Example 2 — Single Point
$ Input: trees = [[1,2]]
Output: [1.0,2.0,0.0]
💡 Note: With only one tree, the smallest circle is centered at that tree's location with radius 0.
Example 3 — Two Points
$ Input: trees = [[0,0],[3,4]]
Output: [1.5,2.0,2.5]
💡 Note: For two points, the smallest circle has them as diameter endpoints. Center is midpoint (1.5,2.0) and radius is half the distance: √(9+16)/2 = 2.5.

Constraints

  • 1 ≤ trees.length ≤ 3000
  • trees[i].length == 2
  • -1000 ≤ xi, yi ≤ 1000
  • All the given positions are unique

Visualization

Tap to expand
Erect the Fence II - Welzl's Algorithm INPUT 0 1 2 1 2 (1,1) (2,2) (2,0) (0,2) trees array: [1,1], [2,2] [2,0], [0,2] 4 trees to enclose Goal: Find minimum enclosing circle (MEC) for all trees WELZL'S ALGORITHM 1 Shuffle Points Randomize tree order for expected O(n) time 2 Recursive Build welzl(P, R) where P=points, R=boundary 3 Base Cases |R|=3: circle from 3 pts |P|=0: circle from R 4 Check and Expand If point outside circle, add to boundary R Boundary Set Cases: |R|=0: empty circle |R|=1: radius=0 |R|=2: diameter circle |R|=3: circumcircle FINAL RESULT r center Output: [1.0, 1.0, 1.414213] [x, y, radius] OK - All trees enclosed Center: (1,1) r = sqrt(2) = 1.414 Key Insight: Welzl's algorithm finds the Minimum Enclosing Circle (MEC) with expected O(n) time complexity. The MEC is uniquely determined by at most 3 points on its boundary. The algorithm recursively builds the circle, adding points to the boundary set when they fall outside the current circle. For 4 symmetric points around (1,1), the MEC has center (1,1) and radius sqrt(2) = 1.414213. TutorialsPoint - Erect the Fence II | Welzl's Algorithm
Asked in
Google 15 Facebook 8
12.5K Views
Medium Frequency
~35 min Avg. Time
324 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