Skip to problem
←

Critical Connections in a Network

Hard 0 attempts

You're given n servers and a list of direct connections between them. Identify every critical connection — a bridge edge that, if removed, would split the network and leave some servers unable to reach others.

Function contract

Implement criticalConnections(n, connections). Servers are numbered 0 through n - 1; each pair [u, v] is an undirected edge.

Output: All bridge edges as endpoint pairs. Pair order and endpoint order are ignored. Return [] if removing any single edge leaves the network connected.

Example 1

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

Example 2

Input
n = 2
connections = [[0,1]]
Output
[[0,1]]
Visual Aid
Only edge 1—3 is a bridge
0213Remove 1—3: server 3 is isolated

The triangle has alternate routes. Server 3 has only one connection, so removing that edge disconnects it.

Constraints
  • 2 <= n <= 10^5
  • n - 1 <= connections.length <= 10^5
  • The network is connected and undirected, with no self-loops or duplicate edges.
  • Every endpoint is an integer from 0 to n - 1.
Topics

Iterative Tarjan Bridge Search

Record discovery times and the earliest ancestor reachable from each subtree. When returning from a child, its edge is a bridge if its low-link value is greater than the parent’s discovery time. Explicit frames support long chains.

javascript
function criticalConnections(n, connections) {
  const graph = Array.from({ length: n }, () => []);
  for (const [u, v] of connections) {
    graph[u].push(v);
    graph[v].push(u);
  }
  const disc = Array(n).fill(-1),
    low = Array(n).fill(0),
    parent = Array(n).fill(-1),
    result = [];
  let time = 0;
  for (let start = 0; start < n; start++)
    if (disc[start] === -1) {
      disc[start] = low[start] = time++;
      const stack = [[start, 0]];
      while (stack.length) {
        const frame = stack[stack.length - 1],
          u = frame[0];
        if (frame[1] < graph[u].length) {
          const v = graph[u][frame[1]++];
          if (v === parent[u]) continue;
          if (disc[v] === -1) {
            parent[v] = u;
            disc[v] = low[v] = time++;
            stack.push([v, 0]);
          } else low[u] = Math.min(low[u], disc[v]);
        } else {
          stack.pop();
          const p = parent[u];
          if (p !== -1) {
            low[p] = Math.min(low[p], low[u]);
            if (low[u] > disc[p]) result.push([p, u]);
          }
        }
      }
    }
  return result;
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript