Problem
You get n nodes with the numbers 0 to n - 1. You also get a list edges of undirected edges. Each item [a, b] is an edge between node a and node b.
Return true if the edges make a valid tree. Return false otherwise.
A valid tree has a path between each pair of nodes, and it has no cycle. A cycle is a path that starts and ends at the same node and uses each edge at most one time.
Example 1
- Input:
- n = 5, edges = [[0,1],[1,2],[1,3],[3,4]]
- Output:
- true
- Explanation:
- The edges connect all 5 nodes, and they make no cycle.
Example 2
- Input:
- n = 4, edges = [[0,1],[1,2],[2,0],[2,3]]
- Output:
- false
- Explanation:
- The nodes 0, 1 and 2 make a cycle.
Example 3
- Input:
- n = 4, edges = [[0,1],[2,3]]
- Output:
- false
- Explanation:
- No path goes from node 0 to node 2.
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
- edges[i].length == 2
- 0 <= a, b < n
- a != b
- No edge occurs two times
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 1 record
No company association
Leetcode 261. Graph Valid Tree
Reported date not specified · 0 source reports
Source snapshot: Nov 12, 2026
View source