sagelearnai

Critical Connections in a Network

Difficulty: Hard · Pattern: Graphs (BFS / DFS) · LeetCode #1192

Servers 0..n−1 are connected by undirected connections. A critical connection is one whose removal disconnects some servers from others. Return all of them, in any order (each as [a, b] in either orientation).

Example

text
n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]  →  [[1,3]]
   0 — 1 — 3
    \ /
     2          (0-1-2 is a cycle; only 1–3 is a bridge)

Hints

  1. Critical connections are bridges. An edge on a cycle is never a bridge.
  2. Number the nodes in DFS discovery order. For each node, compute low = the smallest discovery time reachable from its DFS subtree using at most one back edge.

Approach

Tarjan's bridge-finding in one DFS:

text
dfs(u, parentEdge):
  disc[u] = low[u] = timer++
  for v in adj[u]:
    if v is the parent (via the same edge): skip
    if v unvisited:
        dfs(v, u)
        low[u] = min(low[u], low[v])
        if low[v] > disc[u]: (u, v) is a bridge   # v's subtree can't reach u or above without this edge
    else:
        low[u] = min(low[u], disc[v])             # back edge

O(V + E). With up to 10⁵ nodes, use an iterative DFS in Python to avoid recursion limits. The Python solution here does that. The same low/disc machinery finds articulation points and strongly connected components.

Complexity

Time: O(V + E). Space: O(V + E).

Python solution
def criticalConnections(n, connections):
    adj = [[] for _ in range(n)]
    for i, (a, b) in enumerate(connections):
        adj[a].append((b, i))
        adj[b].append((a, i))
    disc, low = [-1] * n, [0] * n
    res, timer = [], 0
    for s in range(n):
        if disc[s] != -1:
            continue
        disc[s] = low[s] = timer; timer += 1
        stack = [(s, -1, 0)]          # (node, edge id used to enter, next neighbor index)
        while stack:
            u, pe, i = stack[-1]
            if i < len(adj[u]):
                stack[-1] = (u, pe, i + 1)
                v, eid = adj[u][i]
                if eid == pe:
                    continue
                if disc[v] == -1:
                    disc[v] = low[v] = timer; timer += 1
                    stack.append((v, eid, 0))
                else:
                    low[u] = min(low[u], disc[v])
            else:
                stack.pop()
                if stack:
                    p = stack[-1][0]
                    low[p] = min(low[p], low[u])
                    if low[u] > disc[p]:
                        res.append([p, u])
    return res
JavaScript solution
function criticalConnections(n, connections) {
  const adj = Array.from({ length: n }, () => []);
  connections.forEach(([a, b], i) => { adj[a].push([b, i]); adj[b].push([a, i]); });
  const disc = new Array(n).fill(-1), low = new Array(n).fill(0), res = [];
  let timer = 0;
  const dfs = (u, pe) => {
    disc[u] = low[u] = timer++;
    for (const [v, eid] of adj[u]) {
      if (eid === pe) continue;
      if (disc[v] === -1) {
        dfs(v, eid);
        low[u] = Math.min(low[u], low[v]);
        if (low[v] > disc[u]) res.push([u, v]);
      } else low[u] = Math.min(low[u], disc[v]);
    }
  };
  for (let s = 0; s < n; s++) if (disc[s] === -1) dfs(s, -1);
  return res;
}