Graph Valid Tree
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
You're given n nodes labeled 0 to n - 1 and a list of undirected edges. Return true if these edges form a valid tree, and false otherwise.
Understand the problem
In graph terms, a tree is a graph that is both:
- connected: you can get from any node to any other by following edges, and
- acyclic: it has no cycles (no way to walk in a loop and come back to where you started without reusing an edge).
There's no root or left/right here: it's the general shape of a tree, just nodes and connections.
Example 1
Input: n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: true
0
/ | \
1 2 3
|
4Everything is connected, and there are no loops.
Example 2
Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: false1 ─ 2 ─ 3 ─ 1 is a cycle.
Example 3
Input: n = 4, edges = [[0, 1], [2, 3]]
Output: falseNo cycles, but {0, 1} and {2, 3} aren't connected to each other.
Constraints
1 <= n <= 20000 <= edges.length <= 5000- No repeated edges or self-loops.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
A tree with n nodes has exactly n - 1 edges; check that first, then add the edges with Union-Find and fail if any edge connects two nodes that are already connected (that edge would close a cycle).
The key insight: a counting shortcut
Try drawing trees with 1, 2, 3, 4 nodes. Each time you add a node to a tree, you connect it with exactly one new edge. So:
A tree with
nnodes has exactlyn - 1edges.
- Fewer than
n - 1edges: there aren't enough to connect everything. Not a tree. - More than
n - 1: there's at least one extra edge, which must close a cycle. Not a tree. - Exactly
n - 1: then "connected" and "no cycle" go together: if one is true, so is the other. So you only need to check one of them.
Checking for a cycle with Union-Find
Union-Find keeps track of which nodes are already connected, in groups (see Number of Connected Components). Add the edges one at a time:
- If the edge's two ends are in different groups, merge the groups.
- If they're already in the same group, there was already a path between them. Adding this edge creates a second path: that's a cycle. Return
false.
If every edge merges two different groups, there's no cycle, and with n - 1 edges, the graph is a tree.
Step by step
n = 4, edges = [[0, 1], [1, 2], [2, 0]]: exactly n - 1 = 3 edges, so the count check passes.
| Edge | Groups before | Same group? | Action |
|---|---|---|---|
[0, 1] | {0} {1} {2} {3} | no | merge → {0,1} {2} {3} |
[1, 2] | {0,1} {2} {3} | no | merge → {0,1,2} {3} |
[2, 0] | {0,1,2} {3} | yes | cycle! → false |
Notice node 3 is also disconnected: the cycle "used up" an edge that should have connected it. That's why checking only one property is enough.
The code
The reference solution is below, with comments on every important line.
How fast is it?
With V nodes and E edges:
- Time: about O(V + E). Each
findis nearly constant thanks to path compression. - Memory: O(V) for the
parentarray.
Common mistakes
- Only checking for cycles. Example 3 has no cycle, but isn't connected. The edge count check catches it.
- Only checking connectivity with more than
n - 1edges: everything can be connected and still contain a cycle. - Forgetting
n = 1with no edges. A single node is a valid tree:0edges= n - 1.
Going deeper
- DFS works too: after the edge count check, run a search from node
0and count how many nodes you reach. It's a tree exactly when you reach alln. - The same "an edge inside one group closes a cycle" idea finds the redundant connection in a graph, and it's the heart of Kruskal's algorithm for building a minimum spanning tree.
Reference solution
/**
* @param {number} n
* @param {number[][]} edges
* @return {boolean}
*/
export default function validTree(n, edges) {
// A tree with n nodes has exactly n - 1 edges. With exactly that many,
// "no cycle" also guarantees "connected", so we only need to look for a cycle.
if (edges.length !== n - 1) return false
// Union-Find: every node starts as its own group, pointing to itself.
const parent = Array.from({ length: n }, (_, i) => i)
// Follow parent pointers up to the group's representative.
function find(x) {
while (parent[x] !== x) {
parent[x] = parent[parent[x]] // path compression: skip a level for next time
x = parent[x]
}
return x
}
for (const [a, b] of edges) {
const rootA = find(a)
const rootB = find(b)
// Already connected some other way: this edge would close a cycle.
if (rootA === rootB) return false
parent[rootA] = rootB // merge the two groups
}
return true
}export default function validTree(n: number, edges: number[][]): boolean {
// A tree with n nodes has exactly n - 1 edges. With exactly that many,
// "no cycle" also guarantees "connected", so we only need to look for a cycle.
if (edges.length !== n - 1) return false
// Union-Find: every node starts as its own group, pointing to itself.
const parent = Array.from({ length: n }, (_, i) => i)
// Follow parent pointers up to the group's representative.
function find(x: number): number {
while (parent[x] !== x) {
parent[x] = parent[parent[x]] // path compression: skip a level for next time
x = parent[x]
}
return x
}
for (const [a, b] of edges) {
const rootA = find(a)
const rootB = find(b)
// Already connected some other way: this edge would close a cycle.
if (rootA === rootB) return false
parent[rootA] = rootB // merge the two groups
}
return true
}def valid_tree(n: int, edges: list[list[int]]) -> bool:
# A tree with n nodes has exactly n - 1 edges. With exactly that many,
# "no cycle" also guarantees "connected", so we only need to look for a cycle.
if len(edges) != n - 1:
return False
# Union-Find: every node starts as its own group, pointing to itself.
parent = list(range(n))
# Follow parent pointers up to the group's representative.
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression: skip a level for next time
x = parent[x]
return x
for a, b in edges:
root_a, root_b = find(a), find(b)
# Already connected some other way: this edge would close a cycle.
if root_a == root_b:
return False
parent[root_a] = root_b # merge the two groups
return True