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 n nodes, numbered 0 to n - 1, and a list edges. Each edge [a, b] is a line between nodes a and b that can be followed in both directions. Return true if the nodes and edges form a valid tree: every node can be reached from every other node, and there is no loop, also called a cycle. Otherwise return false.

Example 1
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Example 2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Explanation: 1 - 2 - 3 - 1 is a cycle.
Solution

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.

Example 2 with five nodes. Adding the edges one by one: 0 - 1, 1 - 2 and 2 - 3 each join two groups, going from 5 groups to 2. The edge 1 - 3 closes a loop, because 1 and 3 are already in one group. Then 1 - 4 joins the last two groups.

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]] has 4 edges for 5 nodes, yet 1 - 3 closes a loop and node 4 is left on its own.

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]] on 4 nodes: neither edge closes a loop, yet node 0 can never reach node 2. A version of the method without the count check returns true for that input.

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. The root links to itself.

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 works in these steps:

  1. First, compare edges.length with n - 1, and return false if they differ.
  2. Create the array parent, with one entry per node, and set parent[i] = i, so every node starts as the root of its own group.
  3. Go through the edges one by one. For each edge, find the roots of its two ends with the helper find, and keep them in rootA and rootB. find follows the parent links up to the root, with path halving on the way.
  4. If rootA equals rootB, both ends are already in one group and the edge closes a loop, so return false. Otherwise, join the two groups with parent[rootA] = rootB.
  5. If every edge passes, all n - 1 edges joined two groups, so return true.

The main method runs both examples, Example 2 without its last edge, two separate edges on 4 nodes, one node with no edges, and two nodes with no edges.

Java
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:

Output
true
false
false
false
true
false

Example 1 prints true and Example 2 prints false. Example 2 never gets past the count: it has 5 edges for 5 nodes, not 4. The third false has a different cause. [[0,1],[1,2],[2,3],[1,3]] passes the count with 4 edges, and the check stops at 1 - 3, whose two ends already share a root.

The fourth line, false for [[0,1],[2,3]] on 4 nodes, comes from the count, since 2 edges is not 3. The last two lines are the smallest inputs. One node with no edges prints true, because 0 edges is exactly n - 1 and a single node is a tree. Two nodes with no edges print false, since nothing connects them.

Complexity

The work is the count check, setting up parent, and two find calls for each of at most n - 1 edges.

  • Time: O(n log n), because each of the at most n - 1 edges makes two find calls, and with path halving alone each call costs O(log n) on average over the run.
  • Space: O(n), because parent holds one entry per node, and find is a loop rather than recursion, so it needs no extra call stack.

The same Union-Find counting idea solves Number of Operations to Make Network Connected.