Graph Valid Tree
Medium
Topics
Given n nodes labeled 0..n-1 and a list of undirected edges, return true if the graph is a valid tree (fully connected and acyclic).
Example 1
A valid tree needs both halves: fully connected and no cycle. With 5 nodes that means exactly 4 edges and one component, which holds here, so the answer is
true.Nodes are drawn on a circle; an edge list says nothing about layout, only about connections.
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] Output: true
Example 2
This fails the tree test: the highlighted edge closes a cycle. A tree needs exactly
n-1 edges and one component — edge count alone is not enough.Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] Output: false
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
Editorial — intuition, approach, complexity and pitfalls
Intuition
A graph is a tree iff it has exactly n - 1 edges AND is connected. Those two conditions together forbid both cycles and disconnection.
Approach
- If the edge count is not n-1, it cannot be a tree.
- Otherwise count connected components with union-find.
- It is a valid tree iff there is exactly one component.
Dry Run
n = 5, edges 0-1 0-2 0-3 1-4
A tree is exactly "connected and acyclic", and with n - 1 edges the two collapse
into one check. len(edges) = 4 = n - 1, so continue:
edge 0-1 roots 0 and 1 differ, union par [1, 1, 2, 3, 4]
edge 0-2 roots 1 and 2 differ, union par [1, 2, 2, 3, 4]
edge 0-3 roots 2 and 3 differ, union par [2, 2, 3, 3, 4]
edge 1-4 roots 3 and 4 differ, union par [2, 3, 3, 4, 4]
every edge joined two distinct components, so no edge was ever redundant
answer true
n = 5, edges 0-1 1-2 2-3 1-3 1-4
len(edges) = 5, which is not n - 1 = 4, so false without any union-find at all
answer false
The arithmetic is the whole trick. A graph on n nodes with n - 1 edges is a tree
if and only if it has no cycle: too few edges and it cannot be connected, too
many and it must have a cycle. So checking the count first lets the union-find
pass test only for cycles, and connectivity follows for free.
Neither check alone is sufficient, and it is easy to convince yourself otherwise.
Drop the count check and n = 4 with edges 0-1 and 2-3 returns true -- no cycle,
but two separate components and no tree. Drop the union-find and a graph with the
right edge count but a triangle plus an isolated node slips through.
Watch par mutate as path compression rewrites it. The roots reported are not the
values stored a moment earlier, which is why find is called rather than par read
directly.Complexity
- Time — O((V+E) alpha): union-find over the edges.
- Space — O(V): parent array.
Common Pitfalls
- The n-1 edge check alone is not enough — you also need connectivity.
Full Solution — all languages
class Solution:
def validTree(self, n, edges):
if len(edges) != n - 1: return False
par = list(range(n))
def find(x):
while par[x] != x:
par[x] = par[par[x]]; x = par[x]
return x
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb: return False
par[ra] = rb
return Trueimport java.util.*;
class Solution {
public boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) return false;
int[] par = new int[n];
for (int i = 0; i < n; i++) par[i] = i;
for (int[] e : edges) {
int ra = find(par, e[0]), rb = find(par, e[1]);
if (ra == rb) return false;
par[ra] = rb;
}
return true;
}
private int find(int[] par, int x) {
while (par[x] != x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool validTree(int n, vector<vector<int>>& edges) {
if ((int)edges.size() != n - 1) return false;
vector<int> par(n);
for (int i = 0; i < n; i++) par[i] = i;
function<int(int)> find = [&](int x) -> int {
while (par[x] != x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
};
for (auto& e : edges) {
int ra = find(e[0]), rb = find(e[1]);
if (ra == rb) return false;
par[ra] = rb;
}
return true;
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {boolean}
*/ var validTree = function(n, edges) {
if (edges.length !== n - 1) return false;
const par = [];
for (let i = 0; i < n; i++) par[i] = i;
const find = (x) => {
while (par[x] !== x) {
par[x] = par[par[x]];
x = par[x];
}
return x;
};
for (const [a, b] of edges) {
const ra = find(a), rb = find(b);
if (ra === rb) return false;
par[ra] = rb;
}
return true;
};
Asked at
Snowflake