Introduction
Graph Valid Tree is a classic Union Find problem.
You are given:
- n nodes labeled from 0 to n-1
- Undirected edges
Goal:
Determine whether the graph forms a valid tree.
A valid tree must:
- Be connected
- Contain no cycles
Example
Input
n = 5edges = [[0,1],[0,2],[0,3],[1,4]]Output
true Explanation
0|\
| \
1 2
|
4
|
3
All nodes are connected and no cycle exists.
Key Observation
A graph is a valid tree only if:
- Number of edges = n - 1
- No cycle exists
Union Find helps detect cycles efficiently.
Algorithm
- Check if edges count equals n - 1.
- Initialize DSU.
- Process every edge.
- If both nodes have same parent, cycle found.
- Otherwise union them.
- If no cycle exists, return true.
Dry Run
Input
n = 5
edges = [[0,1],[0,2],[0,3],[1,4]]Edge (0,1)
Union
Edge (0,2)
Union
Edge (0,3)
Union
Edge (1,4)
Union
No cycle found.
Number of edges:
4 = n - 1 Answer:
trueApproach : Union Find (DSU)
Start with every node as its own component.
If an edge connects two nodes already belonging to the same component, a cycle exists.
If no cycle exists and edges count equals n-1, the graph is a valid tree.