Graph Valid Tree – Solution & Complexity
Solution Walkthrough
Step 1: Use the n - 1 edge shortcut
- Any tree with
nvertices must have exactlyn - 1edges. Iflen(edges) != n - 1, you can immediately returnFalse. - Note that
len(edges) == n - 1alone is not enough: a triangle plus an isolated vertex (n = 4, 3 edges) hasn - 1edges but is neither connected nor acyclic.
- Any tree with
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), iffind(u) == find(v)returnFalse; otherwise union them. If alln - 1edges merge distinct components, returnTrue.
- Once
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 andO(n)space.
- With path compression and union by rank, each edge takes
Step 4: Common mistakes
- Checking only
len(edges) == n - 1without verifying connectivity/acyclicity. - In a DFS solution, forgetting to ignore the immediate
parentedge so undirected edges look like 2-node cycles.
- Checking only
Part of Blind 75 · NeetCode 150