Graph Valid Tree
Decide whether a list of edges joins n nodes into one tree, with no loops and no node left out.
There are nedges[a, b]truefalse
Example 1
Output: true
Example 2
Output: false
Explanation: 1 - 2 - 3 - 1 is a cycle.
The Idea
Think of five towns and some roads between them, each road open in both directions. Each town is a node and each road an edge. The roads form a tree when you can drive from any town to any other, and no road trip brings you back to your start without turning around.
Example 1 is like that. Node 0 has edges to 1, 2 and 3, and node 1 has an edge to 4. From 4 you reach 0 through 1, and from 0 you reach 2 and 3, so every node is reachable. There is no loop either, so the answer is true
Example 2 has a loop: from 1 you can go to 2, then to 3, and the edge 1 - 3 takes you straight back to 1. So how can a program check both things, every node reachable and no loop, without tracing paths by hand?
Try adding the edges one at a time and watch the nodes fall into groups. A group here is a set of nodes that the edges added so far connect to each other. Look at the picture below, which does this for Example 2.
In the row labelled "start", no edge has been added, so each of the 5 nodes is a group on its own. The edges 0 - 1, 1 - 2 and 2 - 3 each join two groups, and the number of groups drops to 2: the group of 0, 1, 2 and 3, and node 4 alone.
In the orange row, marked "closes a loop", the edge 1 - 3 arrives. Nodes 1 and 3 are already in one group, so this edge joins nothing; it closes the loop instead, and the number of groups stays at 2. The last edge, 1 - 4, joins the two remaining groups into one.
So every edge does one of two things: it joins two groups and lowers the number of groups by one, or it closes a loop. Going from n groups to one takes exactly n - 1 joining edges. A tree has no loop, so a tree on n nodes has exactly n - 1 edges, and every one of them joins two groups.
Example 2 has 5 edges for 5 nodes, one more than a tree can have, and the extra one is 1 - 3.
Solution Approach
Turning that idea into code means settling three things: what the edge count tells us, how to keep track of the groups, and how to find a node's group quickly.
What the edge count tells us
Is counting the edges enough? A wrong count rules a tree out at once. Fewer than n - 1 edges cannot join n groups into one, and more than n - 1 means at least one edge closes a loop.
Exactly n - 1 edges can still hide a loop, though. Take Example 2 without its last edge: [[0,1],[1,2],[2,3],[1,3]]
With exactly n - 1 edges, one more check settles it. If none of those edges closes a loop, all n - 1 join two groups, and the n nodes end up as one group. So after the count, the code only looks for an edge whose two ends are already in one group.
The count is needed the other way round too. Looking only for loops accepts [[0,1],[2,3]]true
Keeping track of the groups
How do we know which group a node is in? The simplest way is to write a group number next to each node. But then joining two groups means renumbering every node of one of them, which can take n steps for a single edge.
A cheaper way lets each group choose one member as its leader, called the root. Every node keeps a link to another node of its group, closer to the root, in an array named parent
To find a node's group, follow the links until a node links to itself: that node is the root, and two nodes are in one group exactly when they reach the same root. To join two groups, point one root at the other, which is a single change. This structure is called Union-Find, or disjoint set union, after its two operations: find a node's group, and join (union) two groups.
Finding a root quickly
Can following the links get slow? If groups are joined in an unlucky order, the links can form a long chain, and every search walks the whole of it. A small change, called path halving, keeps chains short: while walking up, each node passed is pointed at its grandparent, the node two links up. Every search then leaves the chain shorter for the next one.
Java Solution
The method validTree
- First, compare
withedges.length , and returnn - 1 if they differ.false - Create the array
, with one entry per node, and setparent , so every node starts as the root of its own group.parent[i] = i - Go through the edges one by one. For each edge, find the roots of its two ends with the helper
, and keep them infind androotA .rootB follows thefind links up to the root, with path halving on the way.parent - If
equalsrootA , both ends are already in one group and the edge closes a loop, so returnrootB . Otherwise, join the two groups withfalse .parent[rootA] = rootB - If every edge passes, all n - 1 edges joined two groups, so return
.true
The main
public class GraphValidTree {
public static boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) {
return false; // a tree on n nodes has exactly n - 1 edges
}
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i; // every node starts as its own group
}
for (int[] edge : edges) {
int rootA = find(parent, edge[0]);
int rootB = find(parent, edge[1]);
if (rootA == rootB) {
return false; // both ends already in one group: a loop
}
parent[rootA] = rootB; // join the two groups into one
}
return true; // n - 1 joins leave a single group
}
private static int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // skip a step for later searches
x = parent[x];
}
return x;
}
public static void main(String[] args) {
System.out.println(validTree(5, new int[][] {{0, 1}, {0, 2}, {0, 3}, {1, 4}}));
System.out.println(validTree(5, new int[][] {{0, 1}, {1, 2}, {2, 3}, {1, 3}, {1, 4}}));
System.out.println(validTree(5, new int[][] {{0, 1}, {1, 2}, {2, 3}, {1, 3}}));
System.out.println(validTree(4, new int[][] {{0, 1}, {2, 3}}));
System.out.println(validTree(1, new int[][] {}));
System.out.println(validTree(2, new int[][] {}));
}
}
Running it prints:
true
false
false
false
true
false
Example 1 prints truefalsefalse[[0,1],[1,2],[2,3],[1,3]]
The fourth line, false[[0,1],[2,3]]truefalse
Complexity
The work is the count check, setting up parentfind
- Time: O(n log n), because each of the at most n - 1 edges makes two
calls, and with path halving alone each call costs O(log n) on average over the run.find - Space: O(n), because
holds one entry per node, andparent is a loop rather than recursion, so it needs no extra call stack.find
The same Union-Find counting idea solves