05. Critical Connections in a Network (Tarjan's Bridges)
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:
- Tracking Arrays: Maintain
discoveryTimearray andlowestTimearray initialized to-1. - DFS Logic
dfs(node, parent, time):- Set
discoveryTime[node] = lowestTime[node] = time++. - For each
neighborin 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.
- Recurse
- If already visited:
lowestTime[node] = Math.min(lowestTime[node], discoveryTime[neighbor]).
- If
- Set
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
n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
4 connected servers.
[0,1,2] forms a cycle, but edge [1,3] is the only path to node 3.
Removing [1,3] disconnects node 3.
[[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.
Bridge condition
low[v] > disc[u]means neighborvcannot reach any ancestor ofu.Tarjan's algorithm finds all network bottlenecks in single DFS pass.
Linear time complexity $O(V + E)$.