Erect the Fence II
Time O(n) on average · Space O(n) · Official statement on LeetCode
Solutions
// Time: O(n) on average
// Space: O(n)
// reference: https://en.wikipedia.org/wiki/Smallest-circle_problem
class Solution {
public:
vector<double> outerTrees(vector<vector<int>>& trees) {
random_shuffle(begin(trees), end(trees));
vector<vector<double>> boundaries;
const auto& result = Welzl(trees, &boundaries, 0);
return {result.first[0], result.first[1], result.second};
}
private:
pair<vector<double>, double> Welzl(
const vector<vector<int>>& points,
vector<vector<double>> *boundaries,
int curr) {
if (curr == size(points) || size(*boundaries) == 3) {
return trivial(*boundaries);
}
vector<double> p = {double(points[curr][0]), double(points[curr][1])};
const auto& result = Welzl(points, boundaries, curr + 1);
if (!empty(result.first) && inside(result, p)) {
return result;
}
boundaries->emplace_back(move(p));
const auto& result2 = Welzl(points, boundaries, curr + 1);
boundaries->pop_back();
return result2;
}
pair<vector<double>, double> trivial(const vector<vector<double>>& boundaries) { // circumscribed circle
if (empty(boundaries)) {
return {{}, 0.0};
}
if (size(boundaries) == 1) {
return {boundaries[0], 0.0};
}
if (size(boundaries) == 2) {
return circle_from_2_points(boundaries[0], boundaries[1]);
}
return circle_from_3_points(boundaries[0], boundaries[1], boundaries[2]);
}
double dist(const vector<double>& a, const vector<double>& b) {
return sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]));
}
bool inside(const pair<vector<double>, double>& c, const vector<double>& p) {
static const double EPS = 1e-5;
return dist(c.first, p) < c.second + EPS;
}
vector<double> circle_center(int bx, int by, int cx, int cy) {
double B = bx * bx + by * by;
double C = cx * cx + cy * cy;
double D = bx * cy - by * cx;
return {(cy * B - by * C) / (2 * D), (bx * C - cx * B) / (2 * D)};
}
pair<vector<double>, double> circle_from_2_points(
const vector<double>& A,
const vector<double>& B) {
vector<double> C = {(A[0] + B[0]) / 2.0, (A[1] + B[1]) / 2.0};
return {C, dist(A, B) / 2.0};
}
pair<vector<double>, double> circle_from_3_points(
const vector<double>& A,
const vector<double>& B,
const vector<double>& C) {
vector<double> I = circle_center(B[0] - A[0], B[1] - A[1], C[0] - A[0], C[1] - A[1]);
I[0] += A[0];
I[1] += A[1];
return {I, dist(I, A)};
}
};
Beginner Explanation
What is Erect the Fence II?
Erect the Fence II (LeetCode #1924) is a Hard problem that primarily trains geometry.
How to think about it
- Restate the goal in your own words before coding.
- Work a tiny example by hand so the invariant becomes obvious.
- Identify the pattern — this problem aligns with welzls algorithm.
- Only then translate the idea into code.
Why this problem matters
Hard problems force you to combine patterns and prove complexity carefully — interview gold. Official solution notes mention: Welzl's Algorithm.
AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.
Interview Walkthrough
Interview approach for Erect the Fence II
Opening (30–60 seconds)
- Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
- State a brute force so the interviewer knows you can solve it naively.
- Propose the optimal direction tied to welzls algorithm.
Core solution narrative
- Define the state you track (pointers, DP cell, set membership, stack top, etc.).
- Explain the transition when you process the next element.
- Call out time (O(n) on average) and space (O(n)) before coding.
- Code cleanly; narrate variable names.
What interviewers listen for
- Correctness on edge cases
- Complexity honesty
- Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)
Follow-up questions they may ask
- Can you solve it with less memory?
- What if the input stream is infinite / doesn't fit in RAM?
- How would tests look for adversarial inputs?
Optimized Approach
Optimized solution notes
The reference solutions on AlgoForge target O(n) on average time and O(n) space.
Pattern focus: welzls algorithm
Use the pattern as a checklist:
- welzls algorithm — confirm the invariant holds after each step
Multiple methods appear in the source solutions — compare them and explain when each is preferable.
Implementation tips
- Prefer readable names over micro-optimizations in interviews.
- Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
- After AC-level logic, re-scan for off-by-one and null checks.
Complexity Analysis
Complexity
| Measure | Bound |
|---|---|
| Time | O(n) on average |
| Space | O(n) |
How to justify this in an interview
- Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
- Space: include hash maps, recursion stack, and output allocation when the problem asks for it.
If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.
Common Mistakes
Common mistakes on Erect the Fence II
- Skipping edge cases — empty collections, single-element inputs, max constraints.
- Wrong invariant for welzls algorithm — updating state too early or too late.
- Mutating input unexpectedly when the problem forbids it.
- Off-by-one in windows, ranges, or binary search bounds.
- Ignoring overflow / precision for integer arithmetic problems.
- Overengineering — jumping to an advanced structure when a simpler approach works.
Alternative Approaches
Alternatives
The source file includes more than one method. Compare:
- Primary optimized path — best complexity for typical interviews.
- Secondary approach — often brute force, sorting-based, or space-optimized variant.
Practice articulating when you would pick each (constraints, readability, follow-ups).
Edge Cases
Edge cases checklist
- Minimum input size
- Maximum input size / time limits
- Duplicates and already-sorted input
- Negative numbers / zeros (if applicable)
- Disconnected structures (graphs/trees)
- Single path vs branching recursion depth
Pattern Recognition
Spotting this pattern
Signal phrases that point to welzls algorithm:
- Sorted input or ability to sort without changing the answer class
- Need for contiguous subarray / substring → consider sliding window
- Need for O(1) membership → hash set/map
- Optimal substructure + overlapping subproblems → DP
- Connectivity / components → graph DFS/BFS or Union-Find
Primary topics: geometry.
Follow-up Interview Questions
Follow-ups
- How does the solution change if the input is a stream?
- Can you solve it in-place?
- What if duplicates must be handled differently?
- How would you parallelize the approach?
- Design tests that would break a buggy implementation.
Practice Recommendations
What to practice next
- Re-solve Erect the Fence II in a second language (cpp, python).
- Drill 3–5 more problems tagged geometry.
- Teach the solution out loud in under 5 minutes.
- Add this problem to your revision calendar in 3 days and 14 days.
Visualization
Study checklist
- Read the official problem statement on LeetCode
- Solve on paper / whiteboard first
- Implement the welzls algorithm approach
- Verify edge cases from the checklist
- State time and space complexity aloud
- Compare with the AlgoForge reference solution
- Schedule a revision session
Revision notes
Erect the Fence II (#1924) — Hard. Pattern: welzls algorithm. Complexity: O(n) on average time / O(n) space. Re-derive the invariant before coding.
FAQs
What is the time complexity of Erect the Fence II?+
The reference solutions aim for O(n) on average time and O(n) space. Always re-derive complexity from the code you write in the interview.
What pattern does Erect the Fence II use?+
It primarily maps to welzls algorithm, within the broader topic of geometry.
Is Erect the Fence II good for interviews?+
Yes — as a Hard problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.
Where can I read the official statement?+
Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/erect-the-fence-ii/