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: Find Smallest Enclosing CircleInput: Tree Locations(1,1)(2,2)(2,0)(0,2)Output: Optimal FenceCenterFind the center (x,y) and radius r of the smallest circleResult: [1.0, 1.0, 1.414213]
Understanding the Visualization
1
Input Trees
Given 2D coordinates of trees in the garden
2
Find Circle
Calculate center and radius of smallest enclosing circle
3
Output Result
Return [center_x, center_y, radius] as array
Key Takeaway
🎯 Key Insight: The smallest enclosing circle is uniquely determined by at most 3 points on its boundary
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