Critical Connections in a Network

Find every connection in a server network whose removal would cut some servers off from the others.

A network has n servers, numbered 0 to n - 1. Each entry [a, b] in the list connections joins servers a and b, and a connection works in both directions. A connection is critical if removing it leaves some server unable to reach some other server. Return all critical connections, in any order.

Example 1
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: servers 0, 1 and 2 are joined in a triangle, so any one of those three connections can go and the other two still link them. Server 3 is joined only by 1 - 3.
Example 2
Input: n = 2, connections = [[0,1]]
Output: [[0,1]]
Solution

The Idea

Picture a few servers in a room, wired together with cables. A cable can be unplugged or cut, so it is worth knowing which single cable would split the network if it failed. In Example 1, servers 0, 1 and 2 are wired in a triangle, and server 3 has one cable, to server 1.

Try cutting the cables one at a time. Cut 0 - 1, and server 0 still reaches 1 by going through 2. The same is true for 1 - 2 and for 2 - 0. Cut 1 - 3, though, and server 3 is on its own. So 1 - 3 is the only critical connection.

What made the triangle cables safe? Each one is part of a loop, so the rest of the loop is a detour around it. A cable that lies on no loop has no detour. So the question becomes: which cables lie on no loop, and can we find them without cutting each cable and checking the whole network again?

We can, with one walk through the network. Start at server 0 and keep following cables to servers not visited yet, going as deep as possible before turning back. A walk like this is called a depth-first search, or DFS. Number the servers in the order the walk first reaches them, and call that number the server's visit time.

Look at the picture below. The blue arrows are the walk: 0, then 1, then 2. At server 2, the cable to 0 leads to a server visited earlier, drawn as the dashed arrow labelled "back edge". A cable like that, back to an earlier server, is called a back edge, and it closes a loop.

Example 1: servers 0, 1 and 2 form a triangle and server 3 hangs off server 1. The walk goes 0, 1, 2, then 3. The back edge 2 to 0 lets servers 1 and 2 reach back to visit time 0. Server 3 reaches back only to its own visit time 3, so the connection from 1 to 3 is critical.

Server 2 has no unvisited neighbour left, so the walk returns to 1 and follows the orange arrow to server 3, which gets visit time 3. Each box also says how far back a server reaches: the smallest visit time that the server, or any server the walk reached from it, can get to with one back edge.

Server 2 reaches back to 0 through the back edge 2 to 0. Server 1 reaches back to 0 as well, because the walk reached 2 from 1. Server 3 has no cable except the one it came in by, so it reaches back only to its own visit time, 3.

That is the key insight. The walk reached 3 from 1, and server 3 cannot reach back to 1 or anything earlier, so there is no way around the cable 1 - 3 and it is critical. Server 2 reaches back to 0, earlier than 1, so the cable 1 - 2 sits on a loop and is safe.

Solution Approach

Turning that idea into code means settling five things: storing the network, what to record for each server, the test for a critical connection, which cable to ignore, and networks in several pieces. First, though, a look at why cutting each cable in turn is too slow.

Cutting each connection in turn

Why not do what we did by hand? Remove one connection, walk the network again, and see whether the walk still reaches every server it reached before. With n servers and E connections, each check takes about n + E steps, and there is one check per connection. That is about E × (n + E) steps, while the single walk with visit times needs about n + E.

Storing the network as an adjacency list

How does the walk find a server's cables quickly? Before walking, the code gives every server a list of its neighbours, the servers it has a cable to. A connection [a, b] goes into both a's list and b's list, because cables work both ways. These lists together are called an adjacency list. For Example 1 they are 0: [1, 2], 1: [0, 2, 3], 2: [1, 0] and 3: [1].

Visit times and how far back a server reaches

What does the walk record for each server? Two numbers, kept in two arrays. disc[u] holds the visit time of server u (disc is short for discovery), and -1 means u is not visited yet. low[u] holds how far back u reaches, the "reaches back to" value in the picture.

low[u] starts equal to disc[u] and can only go down, in two ways. A back edge from u to an earlier server v lowers it to disc[v]. When the walk returns to u from a server v it reached from u, it lowers to low[v]. Back in server 1, for example, low[1] drops from 1 to low[2], which is 0.

The test for a critical connection

When is a cable critical? Take a cable u - v that the walk followed from u to v. It is critical when low[v] > disc[u]: neither v nor any server the walk reached from v can get back to u or earlier, so cutting u - v cuts them off. In Example 1, low[3] is 3 and disc[1] is 1, so 1 - 3 is critical. For 1 - 2, low[2] is 0, not greater than 1, so it is safe.

In graph theory a critical connection is called a bridge, and this way of finding all bridges in one walk is known as Tarjan's bridge-finding algorithm.

Ignoring the cable we came in by

Which cables count as back edges? Server 3's list holds 1, and server 1 was visited earlier. If that counted, low[3] would drop to 1, and 1 - 3 would fail the test. The same happens on every cable the walk follows, so nothing would ever be reported. So at each server the walk remembers the server it came from, called its parent, and skips that one cable.

Networks in several pieces

What if some servers cannot reach each other at all? A walk from server 0 then never visits them. So the code tries every server in turn and starts a new walk from each one whose disc is still -1. The cables in each piece are tested the same way.

Java Solution

The method criticalConnections and its helper dfs work in these steps:

  1. First, build the adjacency list adj: one empty list per server, then each connection added to the lists of both its servers.
  2. Create the arrays disc and low with n entries each, and fill disc with -1. Set the counter time to 0 and start an empty list bridges for the answer.
  3. Loop over the servers. For each server i whose disc is still -1, start a walk with dfs(i, -1), where -1 means there is no parent.
  4. In dfs(u, parent), give u the next visit time: disc[u] and low[u] both get time, and time goes up by one. Then a loop goes over u's neighbours v, skipping parent.
  5. If v is not visited yet, call dfs(v, u). When it returns, lower low[u] to low[v] if that is smaller, and if low[v] > disc[u], add [u, v] to bridges.
  6. If v was visited already, the cable u - v closes a loop, so lower low[u] to disc[v] if that is smaller.
  7. When every walk is done, return bridges.

The main method runs both examples, then a chain of four servers, a ring of four servers, two separate pairs, and two triangles joined by one connection.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CriticalConnectionsInNetwork {

    private List<List<Integer>> adj;
    private int[] disc;
    private int[] low;
    private int time;
    private List<List<Integer>> bridges;

    public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
        adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<>());
        }
        for (List<Integer> c : connections) {        // each connection goes in both lists
            adj.get(c.get(0)).add(c.get(1));
            adj.get(c.get(1)).add(c.get(0));
        }
        disc = new int[n];
        low = new int[n];
        Arrays.fill(disc, -1);                       // -1 means not visited yet
        time = 0;
        bridges = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (disc[i] == -1) {
                dfs(i, -1);                          // a new piece of the network
            }
        }
        return bridges;
    }

    private void dfs(int u, int parent) {
        disc[u] = low[u] = time++;
        for (int v : adj.get(u)) {
            if (v == parent) {
                continue;                            // not the connection we came in on
            }
            if (disc[v] == -1) {
                dfs(v, u);
                low[u] = Math.min(low[u], low[v]);
                if (low[v] > disc[u]) {              // v's part cannot get back to u or earlier
                    bridges.add(Arrays.asList(u, v));
                }
            } else {
                low[u] = Math.min(low[u], disc[v]);  // a shortcut to an earlier server
            }
        }
    }

    public static void main(String[] args) {
        CriticalConnectionsInNetwork net = new CriticalConnectionsInNetwork();
        System.out.println(net.criticalConnections(4,
                List.of(List.of(0, 1), List.of(1, 2), List.of(2, 0), List.of(1, 3))));
        System.out.println(net.criticalConnections(2, List.of(List.of(0, 1))));
        System.out.println(net.criticalConnections(4,
                List.of(List.of(0, 1), List.of(1, 2), List.of(2, 3))));
        System.out.println(net.criticalConnections(4,
                List.of(List.of(0, 1), List.of(1, 2), List.of(2, 3), List.of(3, 0))));
        System.out.println(net.criticalConnections(4, List.of(List.of(0, 1), List.of(2, 3))));
        System.out.println(net.criticalConnections(6,
                List.of(List.of(0, 1), List.of(1, 2), List.of(2, 0),
                        List.of(2, 3), List.of(3, 4), List.of(4, 5), List.of(5, 3))));
    }
}

Running it prints:

Output
[[1, 3]]
[[0, 1]]
[[2, 3], [1, 2], [0, 1]]
[]
[[0, 1], [2, 3]]
[[2, 3]]

The first line, [[1, 3]], is Example 1, and [[0, 1]] below it is Example 2, where the single cable has no detour at all. On the third line, the chain 0 - 1 - 2 - 3, every cable is critical. They come out deepest first, [2, 3] before [1, 2] and [0, 1], because a cable is tested when the walk returns along it.

The ring on the fourth line prints [], since every cable lies on the one loop. The fifth line, [[0, 1], [2, 3]], comes from two separate pairs: the second walk, started from server 2, finds [2, 3]. On the last line only [2, 3], the cable between the two triangles, is critical.

The test must use >, not >=. With low[v] >= disc[u], Example 1 prints [[1, 3], [0, 1]]: low[1] and disc[0] are both 0, so the triangle cable 0 - 1 is wrongly reported, and the ring prints [[0, 1]]. Removing the parent skip instead makes all six lines print [].

Complexity

The work is building the adjacency list plus one walk that visits each server once.

  • Time: O(n + E), because dfs runs only on servers whose disc is still -1, so each of the n servers is visited once, and each of the E connections is looked at twice, once from each end's list.
  • Space: O(n + E), because the adjacency list holds 2E entries, disc and low hold n each, and on a chain of servers the calls to dfs nest n deep.

The walk itself is explained step by step in Depth First Search.