Critical Connections in a Network

Hard Graphs BFS / DFS Basics

Critical Connections in a Network is a hard graphs problem solved with the bfs / dfs basics pattern. The best approach, optimal (same dfs with an explicit stack), runs in O(V + E) time and O(V + E) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (remove each link) up.

Problem

A data center has n servers numbered 0 to n - 1. They are joined by undirected network links given as connections, where connections[i] = [a, b] is a link between servers a and b. Using these links, every server can reach every other server, directly or through others.

A link is critical if removing it leaves some server unable to reach some other server. Return all critical links. You may return them in any order, and each link may be written as [a, b] or [b, a].

Examples

Example 1

Input
n = 5, connections = [[0, 1], [1, 2], [2, 0], [1, 3], [3, 4]]
Output
[[1, 3], [3, 4]]
Why
Servers 0, 1 and 2 form a loop, so any one of those links can fail and the loop still joins them. The links 1-3 and 3-4 have no backup: cutting either one cuts off server 4 (and server 3 too for 1-3).

Example 2

Input
n = 2, connections = [[0, 1]]
Output
[[0, 1]]
Why
The only link is the only path between the two servers.

Example 3

Input
n = 4, connections = [[0, 1], [1, 2], [2, 3], [3, 0]]
Output
[]
Why
The four servers sit on one ring. Removing any single link still leaves the rest of the ring as a path.

Constraints

  • 2 <= n <= 10^5
  • n - 1 <= connections.length <= 10^5
  • 0 <= a, b <= n - 1 and a != b for each [a, b]
  • No link appears twice, and every server can reach every other one.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (remove each link)O(E · (V + E))O(V + E)
DFS with discovery time and low valueO(V + E)O(V + E)
Optimal (same DFS with an explicit stack)O(V + E)O(V + E)

2DFS with discovery time and low value

TimeO(V + E)Each server is entered once and each link is looked at twice, once from each end.
SpaceO(V + E)The adjacency list, the tin and low arrays, and a recursion stack up to V deep.

Run one DFS from server 0. Give each server a discovery time tin in the order it is first reached. Its low value is the smallest tin it can reach by going down its DFS subtree and then taking at most one link that jumps back up. For a tree link u to v, if low[v] > tin[u], nothing under v has a way back to u or above except this link, so it is a bridge. The parent link is skipped by its index so it is not mistaken for a way back.

  1. Build the adjacency list with link indexes. Set tin[] to -1 for every server.
  2. dfs(u, parentLink): set tin[u] = low[u] = timer++.
  3. For each (v, k) next to u with k != parentLink: if v is unvisited, call dfs(v, k), then low[u] = min(low[u], low[v]), and if low[v] > tin[u] record link k as critical.
  4. If v is already visited, it is an ancestor on a back link: low[u] = min(low[u], tin[v]).
  5. Call dfs(0, -1) and return the recorded links.
class Solution {
    private List<List<int[]>> adj;
    private int[] tin, low;
    private int timer = 0;
    private List<List<Integer>> result;
    private List<List<Integer>> links;

    public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
        links = connections;
        adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int k = 0; k < connections.size(); k++) {
            int a = connections.get(k).get(0), b = connections.get(k).get(1);
            adj.get(a).add(new int[]{b, k});
            adj.get(b).add(new int[]{a, k});
        }
        tin = new int[n];
        low = new int[n];
        Arrays.fill(tin, -1);
        result = new ArrayList<>();
        dfs(0, -1);
        return result;
    }

    private void dfs(int u, int parentLink) {
        tin[u] = low[u] = timer++;
        for (int[] e : adj.get(u)) {
            int v = e[0], k = e[1];
            if (k == parentLink) continue;
            if (tin[v] == -1) {
                dfs(v, k);
                low[u] = Math.min(low[u], low[v]);
                if (low[v] > tin[u]) result.add(links.get(k));
            } else {
                low[u] = Math.min(low[u], tin[v]);
            }
        }
    }
}

3Optimal (same DFS with an explicit stack)

TimeO(V + E)Each server is pushed and popped once, and each adjacency entry is read once.
SpaceO(V + E)The adjacency list, tin, low, the position pointers and the explicit stack, all linear in size.

The low-value DFS is the right algorithm, but a chain of 10^5 servers makes the recursion 10^5 calls deep, which can overflow the call stack. Keep your own stack instead. Each frame stores the server, the link used to enter it, and how far it has got through its adjacency list. When a frame finishes, pass its low value up to the parent and check the bridge rule there.

  1. Build the adjacency list with link indexes. Set tin[] to -1. Push server 0 with parent link -1 and give it tin = low = 0.
  2. Look at the top frame u. If it still has an unread neighbour (v, k): skip it when k is the entry link; if v is new, set tin[v] = low[v] = timer++ and push v with entry link k; otherwise low[u] = min(low[u], tin[v]).
  3. If u has no neighbours left, pop it. If a parent p remains on the stack: low[p] = min(low[p], low[u]), and if low[u] > tin[p] the entry link of u is critical.
  4. When the stack is empty, return the recorded links.
class Solution {
    public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
        List<List<int[]>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int k = 0; k < connections.size(); k++) {
            int a = connections.get(k).get(0), b = connections.get(k).get(1);
            adj.get(a).add(new int[]{b, k});
            adj.get(b).add(new int[]{a, k});
        }
        int[] tin = new int[n], low = new int[n], next = new int[n], entry = new int[n];
        Arrays.fill(tin, -1);
        List<List<Integer>> result = new ArrayList<>();
        int[] stack = new int[n];
        int top = 0, timer = 0;
        stack[top++] = 0;
        entry[0] = -1;
        tin[0] = low[0] = timer++;
        while (top > 0) {
            int u = stack[top - 1];
            if (next[u] < adj.get(u).size()) {
                int[] e = adj.get(u).get(next[u]++);
                int v = e[0], k = e[1];
                if (k == entry[u]) continue;
                if (tin[v] == -1) {
                    tin[v] = low[v] = timer++;
                    entry[v] = k;
                    stack[top++] = v;
                } else {
                    low[u] = Math.min(low[u], tin[v]);
                }
            } else {
                top--;
                if (top > 0) {
                    int p = stack[top - 1];
                    low[p] = Math.min(low[p], low[u]);
                    if (low[u] > tin[p]) result.add(connections.get(entry[u]));
                }
            }
        }
        return result;
    }
}

Edge cases to test

  • A tree (exactly n - 1 links): every link is critical
  • One big ring: no link is critical
  • Two loops joined by a single link: only that link is critical
  • A long chain of 10^5 servers, which breaks recursive code on the call stack
  • Links written as [b, a] instead of [a, b]: the answer may list each pair in either order

Hints

Hint 1

A link is critical when it is not part of any loop. If it sits on a loop, the rest of the loop is a detour around it.

Hint 2

Run one DFS and number the servers in the order you first reach them. For each server, track the smallest number it can reach using its own subtree plus at most one back link.

Hint 3

For a tree link from u down to child v, if the smallest number reachable from v's subtree is still greater than u's number, nothing below v can get back to u or above without that link, so it is critical.

FAQ

What is the best time complexity for Critical Connections in a Network?

Optimal (same DFS with an explicit stack) runs in O(V + E) time and O(V + E) extra space. Each server is pushed and popped once, and each adjacency entry is read once.

Which pattern does Critical Connections in a Network use?

It is a graphs problem that uses the bfs / dfs basics pattern. Other problems with the same pattern: BFS - Normal + Level by Level, DFS - Recursive + Iterative, Clone Graph.

Is there a brute force solution for Critical Connections in a Network?

Yes. Brute force (remove each link) takes O(E · (V + E)) time and O(V + E) space. Try the definition directly.

Which edge cases should I test for Critical Connections in a Network?

A tree (exactly n - 1 links): every link is critical; One big ring: no link is critical; Two loops joined by a single link: only that link is critical; A long chain of 10^5 servers, which breaks recursive code on the call stack; Links written as [b, a] instead of [a, b]: the answer may list each pair in either order.