05. Critical Connections in a Network (Tarjan's Bridges)

Difficulty:HardPattern:Tarjan Bridge Finding DFSTime:O(V + E)Space:O(V + E)

There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections. Return all critical connections (bridges) whose removal disconnects the network.

How It Works & Algorithmic Design

Solves using Tarjan's Bridge Finding DFS Algorithm:

  1. Tracking Arrays: Maintain discoveryTime array and lowestTime array initialized to -1.
  2. DFS Logic dfs(node, parent, time):
    • Set discoveryTime[node] = lowestTime[node] = time++.
    • For each neighbor in adjacency list:
      • If neighbor === parent, continue.
      • If unvisited (discoveryTime[neighbor] === -1):
        • Recurse dfs(neighbor, node, time).
        • Update lowestTime[node] = Math.min(lowestTime[node], lowestTime[neighbor]).
        • Bridge Condition: If lowestTime[neighbor] > discoveryTime[node], connection (node, neighbor) is a critical bridge! Push to result.
      • If already visited: lowestTime[node] = Math.min(lowestTime[node], discoveryTime[neighbor]).

Why This Approach Works Best

Finds all graph bridges in a single pass $O(V + E)$ linear time without testing node removals iteratively.

Example Walkthrough

Input Network

n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]

4 connected servers.

Bridge Analysis

[0,1,2] forms a cycle, but edge [1,3] is the only path to node 3.

Removing [1,3] disconnects node 3.

Output

[[1,3]]

Critical bridge connection.

Answer: Tarjan's Critical Connections implementation

function criticalConnections(n, connections) {
  const adj = Array.from({ length: n }, () => []);
  for (const [u, v] of connections) {
    adj[u].push(v); adj[v].push(u);
  }
  const disc = new Array(n).fill(-1);
  const low = new Array(n).fill(-1);
  const bridges = [];
  let time = 0;
  function dfs(u, parent) {
    disc[u] = low[u] = time++;
    for (const v of adj[u]) {
      if (v === parent) continue;
      if (disc[v] === -1) {
        dfs(v, u);
        low[u] = Math.min(low[u], low[v]);
        if (low[v] > disc[u]) bridges.push([u, v]);
      } else {
        low[u] = Math.min(low[u], disc[v]);
      }
    }
  }
  dfs(0, -1);
  return bridges;
}

Traverse graph via DFS tracking discovery times and low link values to detect bridge edges.

Key Takeaways
  • Bridge condition low[v] > disc[u] means neighbor v cannot reach any ancestor of u.

  • Tarjan's algorithm finds all network bottlenecks in single DFS pass.

  • Linear time complexity $O(V + E)$.