Number of Operations to Make Network Connected

Move spare cables so every computer joins one network, by counting the separate groups of computers.

There are n computers, numbered 0 to n - 1, and a list of cables connections, where connections[i] = [a, b] joins computer a and computer b. Two computers can talk when a chain of cables leads from one to the other. In one operation you may unplug any cable and plug it in between any two computers. Return the fewest operations needed so that every computer can talk to every other, or -1 if that is impossible.

Example 1
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: move cable 1 - 2 so that it joins computer 3 to the others.
Example 2
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2
Example 3
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: 4 cables cannot connect 6 computers.
Solution

The Idea

Picture an office where some computers are wired together and a few sit on their own. There is no new cable to buy. All you can do is unplug a cable from one place and plug it in somewhere else, and you want everyone on one network in as few moves as possible.

Look at the left half of the picture below, which is Example 2. Computers 0, 1, 2 and 3 are wired together, while computers 4 and 5 have no cable at all. Computers that can reach each other, directly or through a chain of cables, form a group. The left half shows three groups, each in its own dashed box: {0, 1, 2, 3}, {4} and {5}. In graph terms, the computers are vertices, the cables are edges, and a group is called a connected component.

Example 2 before and after. Before: computers 0, 1, 2 and 3 form one group, joined by cables 0 - 1, 0 - 2 and 0 - 3, plus spare cables 1 - 2 and 1 - 3. Computers 4 and 5 are groups of their own. After: the spare cables are moved to 3 - 4 and 3 - 5, and all six computers form 1 group.

Which cables can we take away without cutting anyone off? Inside the big group, computer 0 already reaches 1, 2 and 3 through the blue cables 0 - 1, 0 - 2 and 0 - 3. The orange cables, 1 - 2 and 1 - 3, join computers that could already talk through 0. Unplugging either one leaves the group whole, so the picture labels them "spare cables".

Each moved cable can join two groups into one. Three groups need two such joins, and the right half of the picture shows them: the spare cables now run 3 - 4 and 3 - 5, and all six computers form 1 group. That is the answer 2.

Example 3 has the same three groups but one cable fewer. Only 1 - 2 is spare now, so after one move computer 5 is still alone. Could there be too few spare cables even when there are enough cables in total to join every computer? If that never happens, the whole problem comes down to one count: the number of groups.

Solution Approach

Turning that idea into code means settling three things: when the answer is -1, whether there are always enough spare cables otherwise, and how to count the groups. A second way to count the groups, a search that follows the cables, is an option.

When there are too few cables

How many cables does it take to join n computers at all? Start from n computers with no cables, which is n groups. Plugging in one cable joins at most two groups, so the count of groups drops by at most one. Getting down to 1 group therefore takes at least n - 1 cables. In Example 3, six computers need five cables and there are only four, so no amount of moving helps and the answer is -1.

Counting spare cables

With at least n - 1 cables, are there always enough spare ones? Call the number of groups g. A group of computers can be held together with one cable fewer than it has computers, like 0 - 1, 0 - 2 and 0 - 3 for four computers in Example 2. Over all groups, that is n - g needed cables.

Every other cable is spare. With at least n - 1 cables in total, the spare ones number at least (n - 1) - (n - g) = g - 1, which is exactly the number of moves needed. So once the cable check passes, the answer is simply g - 1, and the spare cables never have to be found or counted.

Counting groups with union-find

How do we count the groups? Give each computer a parent, another computer it points to. Following parents from any computer ends at one computer that points to itself, the root, and that root names the computer's group. At the start every computer is its own root, so there are n groups.

Now go through the cables one by one and find the root of each end. Different roots mean the cable joins two groups: point one root at the other, and the count drops by one. The same root means the cable is spare. In Example 2, cables 0 - 1, 0 - 2 and 0 - 3 each join two groups, taking the count from 6 to 3. Cables 1 - 2 and 1 - 3 find the same root at both ends, so the count stays 3.

Finding a root walks up a chain of parents, and chains could grow long. While walking, each computer can be pointed at its parent's parent, which halves the chain for the next walk. Pointing at the grandparent like this is called path halving, and the whole structure of parents, roots and merging is called union-find, or a disjoint set.

Optional: counting groups with a depth-first search

The groups can also be counted by walking the cables. First turn the cable list into an adjacency list: for each computer, the list of computers it has a cable to. For Example 2 that is 0: [1, 2, 3], 1: [0, 2, 3], 2: [0, 1], 3: [0, 1], 4: [] and 5: [].

Then start at each computer that has not been visited yet and follow cables as far as they lead, marking every computer reached. Following one cable as deep as possible before backing up is called a depth-first search (DFS). In Example 2 the searches start at 0, 4 and 5, three starts for three groups. It gives the same answer, but needs the adjacency list as extra memory, so the code below uses union-find.

Java Solution

The method makeConnected works in these steps:

  1. First, compare the number of cables, connections.length, with n - 1. With fewer cables, return -1 straight away.
  2. Create the array parent, one entry per computer, and fill it in a loop so that parent[i] = i: every computer is its own root. Set groups to n.
  3. Loop over the cables. For each cable, call the helper find on both ends to get their roots, a and b. Inside find, a loop follows parents until it reaches a computer that is its own parent, pointing each computer it passes at its grandparent on the way.
  4. If a and b differ, set parent[a] = b to merge the two groups and lower groups by one. If they are equal, the cable is spare and nothing changes.
  5. After the loop, return groups - 1, the number of cables to move.

The main method runs the three examples, three computers already in one chain, a single computer with no cables, and five computers in two groups where the first group has one spare cable.

Java
public class NumberOfOperationsToMakeNetworkConnected {

    public static int makeConnected(int n, int[][] connections) {
        if (connections.length < n - 1) {
            return -1;                         // too few cables, however they are moved
        }
        int[] parent = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;                     // every computer starts as its own group
        }
        int groups = n;
        for (int[] cable : connections) {
            int a = find(parent, cable[0]);
            int b = find(parent, cable[1]);
            if (a != b) {
                parent[a] = b;                 // the cable joins two groups into one
                groups--;
            }                                  // else: a spare cable inside one group
        }
        return groups - 1;                     // one moved cable joins two groups
    }

    private static int find(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];     // path halving: skip one level
            x = parent[x];
        }
        return x;
    }

    public static void main(String[] args) {
        System.out.println(makeConnected(4, new int[][] {{0, 1}, {0, 2}, {1, 2}}));
        System.out.println(makeConnected(6,
                new int[][] {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}}));
        System.out.println(makeConnected(6, new int[][] {{0, 1}, {0, 2}, {0, 3}, {1, 2}}));
        System.out.println(makeConnected(3, new int[][] {{0, 1}, {1, 2}}));
        System.out.println(makeConnected(1, new int[][] {}));
        System.out.println(makeConnected(5,
                new int[][] {{0, 1}, {1, 2}, {2, 0}, {3, 4}}));
    }
}

Running it prints:

Output
1
2
-1
0
0
1

The values 1, 2 and -1 at the top match Examples 1, 2 and 3. The two 0 lines are networks that need no moves. The chain 0 - 1 - 2 is already one group, and a single computer with no cables passes the check, because it needs n - 1 = 0 cables.

Look at the last line, 1. Cables 0 - 1 and 1 - 2 join computers 0, 1 and 2, so cable 2 - 0 finds the same root at both ends and is spare. Cable 3 - 4 forms the second group, and moving 2 - 0 joins the two.

The cable check at the start matters even though the loop never looks for spare cables. Without it, Example 3 returns 2, because its three groups would ask for two moves while only cable 1 - 2 is spare.

Complexity

The work is filling parent once and then two find calls for every cable.

  • Time: O(n + E log n), where E is the number of cables, because filling parent takes n steps and path halving keeps each of the 2E find calls at O(log n) steps when averaged over all the calls.
  • Space: O(n), because parent holds one entry per computer and find is a loop rather than a method calling itself, so it adds nothing on the call stack.

The same union-find setup decides Graph Valid Tree.