Graph Valid Tree - Problem
Given n nodes labeled from 0 to n-1 and a list of undirected edges, determine if these edges form a valid tree.
A valid tree is a connected graph with exactly n-1 edges and no cycles. Think of it like a family tree or organizational chart - every node should be reachable from every other node, but there should be exactly one path between any two nodes.
Key Properties of a Tree:
- ๐ณ Connected: All nodes must be reachable
- ๐ซ Acyclic: No cycles allowed
- ๐ Minimal: Exactly n-1 edges (not more, not less)
Return true if the edges form a valid tree, false otherwise.
Input & Output
example_1.py โ Valid Tree
$
Input:
n = 5, edges = [[0,1],[1,2],[2,3],[1,4]]
โบ
Output:
true
๐ก Note:
This forms a valid tree: 5 nodes with 4 edges, fully connected with no cycles. Node 1 acts as a hub connecting to nodes 0, 2, and 4, with node 3 connected through node 2.
example_2.py โ Has Cycle
$
Input:
n = 5, edges = [[0,1],[1,2],[2,3],[1,4],[3,4]]
โบ
Output:
false
๐ก Note:
This graph contains a cycle: 1โ2โ3โ4โ1. A valid tree cannot have cycles, so this returns false even though all nodes are connected.
example_3.py โ Disconnected Components
$
Input:
n = 4, edges = [[0,1],[2,3]]
โบ
Output:
false
๐ก Note:
This graph has two disconnected components: {0,1} and {2,3}. A valid tree must be fully connected, so this returns false.
Visualization
Tap to expand
Understanding the Visualization
1
Edge Count Check
A tree with n nodes must have exactly n-1 edges
2
Cycle Detection
Use DFS or Union-Find to detect if any cycles exist
3
Connectivity Check
Verify all nodes are reachable from any starting node
Key Takeaway
๐ฏ Key Insight: A valid tree is the minimal connected graph - exactly n-1 edges with full connectivity and zero cycles!
Time & Space Complexity
Time Complexity
O(n + m)
We visit each node once and examine each edge once, where n is nodes and m is edges
โ Linear Growth
Space Complexity
O(n + m)
Space for adjacency list (O(n + m)) plus visited set (O(n)) plus recursion stack (O(n) in worst case)
โก Linearithmic Space
Constraints
- 1 โค n โค 2000
- 0 โค edges.length โค 5000
- edges[i].length == 2
- 0 โค ai, bi < n
- ai โ bi
- No duplicate edges in the input
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code