KatInterview

587. Erect the Fence

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the set of trees that lie on the perimeter of a fence enclosing all trees with the minimum possible length of rope. This is a classic computational geometry problem equivalent to finding the convex hull of a given set of points. The trees on the perimeter are the vertices of the convex hull, including any trees that are collinear and lie on the edges of the hull.

Solution

Erect the Fence in Python

class Solution:
    def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:
        n = len(trees)
        if n <= 3:
            return trees

        # Sort points lexicographically (by x, then by y)
        trees.sort()

        # Cross product helper function
        # > 0 for counter-clockwise (left) turn
        # < 0 for clockwise (right) turn
        # = 0 for collinear points
        def cross_product(p1, p2, p3):
            return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0])

        # Build lower hull
        lower = []
        for p in trees:
            while len(lower) >= 2 and cross_product(lower[-2], lower[-1], p) > 0:
                lower.pop()
            lower.append(p)

        # Build upper hull
        upper = []
        # Iterate in reverse order for the upper hull
        for p in reversed(trees):
            while len(upper) >= 2 and cross_product(upper[-2], upper[-1], p) > 0:
                upper.pop()
            upper.append(p)

        # Combine hulls and remove duplicates using a set of tuples
        hull = set()
        for p in lower:
            hull.add(tuple(p))
        for p in upper:
            hull.add(tuple(p))
        
        return [list(p) for p in hull]

Erect the Fence in Java

class Solution {
    public int[][] outerTrees(int[][] trees) {
        int n = trees.length;
        if (n <= 3) {
            return trees;
        }

        // Sort points lexicographically (by x, then by y)
        Arrays.sort(trees, (p1, p2) -> {
            if (p1[0] != p2[0]) {
                return p1[0] - p2[0];
            }
            return p1[1] - p2[1];
        });

        // Build lower hull
        List<int[]> lower = new ArrayList<>();
        for (int[] p : trees) {
            while (lower.size() >= 2 && crossProduct(lower.get(lower.size() - 2), lower.get(lower.size() - 1), p) > 0) {
                lower.remove(lower.size() - 1);
            }
            lower.add(p);
        }

        // Build upper hull
        List<int[]> upper = new ArrayList<>();
        for (int i = n - 1; i >= 0; i--) {
            int[] p = trees[i];
            while (upper.size() >= 2 && crossProduct(upper.get(upper.size() - 2), upper.get(upper.size() - 1), p) > 0) {
                upper.remove(upper.size() - 1);
            }
            upper.add(p);
        }

        // Combine hulls and remove duplicates
        // Using a Set of Lists to handle uniqueness, as Set<int[]> compares references.
        Set<List<Integer>> hullSet = new HashSet<>();
        for (int[] p : lower) {
            hullSet.add(Arrays.asList(p[0], p[1]));
        }
        for (int[] p : upper) {
            hullSet.add(Arrays.asList(p[0], p[1]));
        }

        int[][] result = new int[hullSet.size()][2];
        int i = 0;
        for (List<Integer> p : hullSet) {
            result[i][0] = p.get(0);
            result[i][1] = p.get(1);
            i++;
        }

        return result;
    }

    // Cross product helper function
    // > 0 for counter-clockwise (left) turn
    // < 0 for clockwise (right) turn
    // = 0 for collinear points
    private int crossProduct(int[] p1, int[] p2, int[] p3) {
        // (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)
        return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0]);
    }
}

Erect the Fence in C++

class Solution {
public:
    vector<vector<int>> outerTrees(vector<vector<int>>& trees) {
        int n = trees.size();
        if (n <= 3) {
            return trees;
        }

        // Sort points lexicographically (by x, then by y)
        sort(trees.begin(), trees.end());

        // Cross product helper function
        auto cross_product = [](const vector<int>& p1, const vector<int>& p2, const vector<int>& p3) {
            // (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)
            return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0]);
        };

        // Build lower hull
        vector<vector<int>> lower;
        for (const auto& p : trees) {
            while (lower.size() >= 2 && cross_product(lower[lower.size()-2], lower.back(), p) > 0) {
                lower.pop_back();
            }
            lower.push_back(p);
        }

        // Build upper hull
        vector<vector<int>> upper;
        for (int i = n - 1; i >= 0; --i) {
            const auto& p = trees[i];
            while (upper.size() >= 2 && cross_product(upper[upper.size()-2], upper.back(), p) > 0) {
                upper.pop_back();
            }
            upper.push_back(p);
        }

        // Combine hulls and remove duplicates
        set<vector<int>> hull_set;
        for (const auto& p : lower) {
            hull_set.insert(p);
        }
        for (const auto& p : upper) {
            hull_set.insert(p);
        }

        return vector<vector<int>>(hull_set.begin(), hull_set.end());
    }
};

Erect the Fence in TypeScript

function outerTrees(trees: number[][]): number[][] {
    const n = trees.length;
    if (n <= 3) {
        return trees;
    }

    // Sort points lexicographically (by x, then by y)
    trees.sort((p1, p2) => {
        if (p1[0] !== p2[0]) {
            return p1[0] - p2[0];
        }
        return p1[1] - p2[1];
    });

    // Cross product helper function
    // > 0 for counter-clockwise (left) turn
    // < 0 for clockwise (right) turn
    // = 0 for collinear points
    const crossProduct = (p1: number[], p2: number[], p3: number[]): number => {
        // (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)
        return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0]);
    };

    // Build lower hull
    const lower: number[][] = [];
    for (const p of trees) {
        while (lower.length >= 2 && crossProduct(lower[lower.length - 2], lower[lower.length - 1], p) > 0) {
            lower.pop();
        }
        lower.push(p);
    }

    // Build upper hull
    const upper: number[][] = [];
    for (let i = n - 1; i >= 0; i--) {
        const p = trees[i];
        while (upper.length >= 2 && crossProduct(upper[upper.length - 2], upper[upper.length - 1], p) > 0) {
            upper.pop();
        }
        upper.push(p);
    }

    // Combine hulls and remove duplicates.
    // A Set of serialized points is used because Set in JS compares objects by reference.
    const hullSet = new Set<string>();
    for (const p of lower) {
        hullSet.add(p.join(','));
    }
    for (const p of upper) {
        hullSet.add(p.join(','));
    }

    const result: number[][] = [];
    hullSet.forEach(pStr => {
        result.push(pStr.split(',').map(Number));
    });

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.