KatInterview

261. Graph Valid Tree

MediumSolutions 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

A graph is a valid tree if and only if it satisfies two fundamental properties:

Solution

Graph Valid Tree in Python

class Solution:
    def validTree(self, n: int, edges: list[list[int]]) -> bool:
        # A graph is a valid tree if it has n-1 edges and is acyclic.
        # This combination implies connectivity.
        
        # Condition 1: A tree must have exactly n-1 edges.
        if len(edges) != n - 1:
            return False

        # Union-Find data structure to detect cycles.
        parent = list(range(n))
        size = [1] * n

        def find(i: int) -> int:
            # Find the root of the set containing element i, with path compression.
            if parent[i] == i:
                return i
            parent[i] = find(parent[i])
            return parent[i]

        def union(i: int, j: int) -> bool:
            # Union the sets containing elements i and j.
            # Returns False if they are already in the same set (cycle detected).
            root_i = find(i)
            root_j = find(j)
            if root_i == root_j:
                return False
            
            # Union by size to keep the tree flat.
            if size[root_i] < size[root_j]:
                parent[root_i] = root_j
                size[root_j] += size[root_i]
            else:
                parent[root_j] = root_i
                size[root_i] += size[root_j]
            return True

        # Condition 2: The graph must be acyclic.
        # We iterate through all edges, and if we find an edge that connects
        # two already connected nodes, we have a cycle.
        for u, v in edges:
            if not union(u, v):
                return False
        
        # If both conditions are met, it's a valid tree.
        return True

Graph Valid Tree in Java

class Solution {
    public boolean validTree(int n, int[][] edges) {
        // A graph with n nodes is a tree if it has n-1 edges and is acyclic.
        if (edges.length != n - 1) {
            return false;
        }

        // Initialize Union-Find data structure.
        UnionFind uf = new UnionFind(n);

        // Process each edge.
        for (int[] edge : edges) {
            int u = edge[0];
            int v = edge[1];
            // If the two nodes are already in the same set, a cycle is detected.
            if (!uf.union(u, v)) {
                return false;
            }
        }
        
        // If all edges are processed and no cycles are found, it's a valid tree.
        // The n-1 edge count ensures connectivity for an acyclic graph.
        return true;
    }

    // Inner class for Union-Find data structure.
    private class UnionFind {
        private int[] parent;
        private int[] size;

        // Constructor
        public UnionFind(int n) {
            parent = new int[n];
            size = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        // Find operation with path compression.
        public int find(int i) {
            if (parent[i] == i) {
                return i;
            }
            parent[i] = find(parent[i]);
            return parent[i];
        }

        // Union operation by size. Returns false if nodes are already connected.
        public boolean union(int i, int j) {
            int rootI = find(i);
            int rootJ = find(j);
            if (rootI == rootJ) {
                return false; // Cycle detected.
            }

            // Union by size for a flatter tree structure.
            if (size[rootI] < size[rootJ]) {
                parent[rootI] = rootJ;
                size[rootJ] += size[rootI];
            } else {
                parent[rootJ] = rootI;
                size[rootI] += size[rootJ];
            }
            return true;
        }
    }
}

Graph Valid Tree in C++

class Solution {
public:
    bool validTree(int n, vector<vector<int>>& edges) {
        // A tree with n nodes must have exactly n-1 edges.
        if (edges.size() != n - 1) {
            return false;
        }

        // Initialize Union-Find data structure.
        parent.resize(n);
        size.resize(n, 1);
        for (int i = 0; i < n; ++i) {
            parent[i] = i;
        }

        // Process each edge and check for cycles.
        for (const auto& edge : edges) {
            // The 'unite' operation returns false if the two nodes are already
            // in the same set, which indicates a cycle.
            if (!unite(edge[0], edge[1])) {
                return false;
            }
        }

        // If all edges are processed without finding a cycle, and the edge count
        // is n-1, the graph is a valid tree.
        return true;
    }

private:
    vector<int> parent;
    vector<int> size;

    // Find operation with path compression.
    int find(int i) {
        if (parent[i] == i) {
            return i;
        }
        return parent[i] = find(parent[i]);
    }

    // Union operation by size.
    // Returns true if the sets were merged, false if they were already the same set.
    bool unite(int i, int j) {
        int root_i = find(i);
        int root_j = find(j);
        if (root_i == root_j) {
            return false; // Cycle detected.
        }

        // Union by size to keep the tree structure flat.
        if (size[root_i] < size[root_j]) {
            swap(root_i, root_j);
        }
        parent[root_j] = root_i;
        size[root_i] += size[root_j];
        
        return true;
    }
};

Graph Valid Tree in TypeScript

function validTree(n: number, edges: number[][]): boolean {
    // A valid tree with n nodes must have exactly n - 1 edges.
    if (edges.length !== n - 1) {
        return false;
    }

    // Union-Find data structure.
    const parent: number[] = Array.from({ length: n }, (_, i) => i);
    const size: number[] = Array(n).fill(1);

    // Find operation with path compression.
    const find = (i: number): number => {
        if (parent[i] === i) {
            return i;
        }
        parent[i] = find(parent[i]);
        return parent[i];
    };

    // Union operation by size.
    // Returns false if a cycle is detected.
    const union = (i: number, j: number): boolean => {
        const rootI = find(i);
        const rootJ = find(j);

        if (rootI === rootJ) {
            return false; // Cycle detected.
        }
        
        // Union by size to keep the tree structure flat.
        if (size[rootI] < size[rootJ]) {
            parent[rootI] = rootJ;
            size[rootJ] += size[rootI];
        } else {
            parent[rootJ] = rootI;
            size[rootI] += size[rootJ];
        }
        
        return true;
    };

    // Process all edges to detect cycles.
    for (const [u, v] of edges) {
        if (!union(u, v)) {
            return false; // Cycle detected.
        }
    }
    
    // If there are n-1 edges and no cycles, the graph is a valid tree.
    return true;
};

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.