Graph Valid Tree – Solution & Complexity

Solution Walkthrough

  1. Step 1: Use the n - 1 edge shortcut

    • Any tree with n vertices must have exactly n - 1 edges. If len(edges) != n - 1, you can immediately return False.
    • Note that len(edges) == n - 1 alone is not enough: a triangle plus an isolated vertex (n = 4, 3 edges) has n - 1 edges but is neither connected nor acyclic.
  2. Step 2: Verify connectivity / acyclicity with Union-Find

    • Once len(edges) == n - 1, the graph is a valid tree if and only if no edge connects two already-connected vertices (no cycle) — which automatically guarantees a single connected component.
    • Initialize parent = [0..n-1]. For each edge (u, v), if find(u) == find(v) return False; otherwise union them. If all n - 1 edges merge distinct components, return True.
  3. Step 3: Optimal Union-Find solution

    • With path compression and union by rank, each edge takes O(alpha(n)) amortized time: O(n + E * alpha(n)) time and O(n) space.
    def valid_tree(n: int, edges: list[list[int]]) -> bool:
        if len(edges) != n - 1:
            return False
        parent = list(range(n))
        rank = [0] * n
    
        def find(x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x
    
        for u, v in edges:
            ru, rv = find(u), find(v)
            if ru == rv:
                return False
            if rank[ru] < rank[rv]:
                parent[ru] = rv
            elif rank[ru] > rank[rv]:
                parent[rv] = ru
            else:
                parent[rv] = ru
                rank[ru] += 1
        return True
  4. Step 4: Common mistakes

    • Checking only len(edges) == n - 1 without verifying connectivity/acyclicity.
    • In a DFS solution, forgetting to ignore the immediate parent edge so undirected edges look like 2-node cycles.

FAQ