Critical Connections in a Network Problem
Description
LeetCode Problem 1192.
There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [a_i, b_i] represents a connection between servers a_i and b_i. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
Example 1:

Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.
Example 2:
Input: n = 2, connections = [[0,1]]
Output: [[0,1]]
Constraints:
2 <= n <= 10^5n - 1 <= connections.length <= 10^50 <= a_i, b_i <= n - 1a_i != b_i- There are no repeated connections.
Solution
Approach: Tarjan's Bridge-Finding DFS
A critical connection is a bridge: an edge whose removal disconnects the graph. Removing each edge and checking connectivity costs O(E · (V + E)), far too slow for 10^5 edges. One depth-first search finds all bridges.
During the DFS, give each server a discovery time disc[u] (1, 2, 3, ... in the order we reach them). Also compute low[u]: the smallest discovery time reachable from u's DFS subtree using tree edges downwards plus at most one edge back up.
- When we see a neighbor
vthat is already visited, we have a back edge, solow[u] = min(low[u], disc[v]). - After returning from a child
v,low[u] = min(low[u], low[v]).
The tree edge u - v is a bridge exactly when low[v] > disc[u]: nothing in v's subtree has an edge to u or to anything discovered before it, so cutting u - v cuts the whole subtree off.
The tricky case is the edge we arrived on. In an undirected graph, u's parent appears in u's neighbor list, and counting it as a back edge would make every low[u] <= disc[parent], hiding every bridge. So we skip the parent. Skipping by vertex is safe here because there are no repeated connections.
Complexity: O(n + E) time, where E is the number of connections, and O(n + E) space for the graph and the recursion.
class Solution:
def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
graph = [[] for _ in range(n)]
for a, b in connections:
graph[a].append(b)
graph[b].append(a)
disc = [0] * n # discovery time, 0 = not visited yet
low = [0] * n # earliest discovery time reachable from the subtree with one back edge
timer = 0
bridges = []
def dfs(u: int, parent: int) -> None:
nonlocal timer
timer += 1
disc[u] = low[u] = timer
for v in graph[u]:
if v == parent:
continue # the tree edge we came along is not a back edge
if disc[v] == 0:
dfs(v, u)
low[u] = min(low[u], low[v])
if low[v] > disc[u]:
bridges.append([u, v]) # v's subtree cannot reach u or above
else:
low[u] = min(low[u], disc[v])
dfs(0, -1) # the network is connected
return bridges