SDE & MLE Prep

1192. Critical Connections in a Network

Problem

Servers 0…n − 1 are joined by undirected connections, and the network is connected. A connection is critical if removing it leaves some server unable to reach another. Return all critical connections, in any order.

Example: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]] → [[1,3]]

Constraints: n ≤ 10⁵.

Tarjan's bridge-finding: DFS assigns discovery time tin[u]; low[u] = smallest tin reachable from u's subtree using at most one back edge. Tree edge (u, v) is a bridge iff low[v] > tin[u] (v's subtree can't reach u or above without it).

0 - 1 - 3            tin: 0:0 1:1 2:2 3:3
 \ /                 low: 0:0 1:0 2:0 3:3
  2                  low[3]=3 > tin[1]=1  -> bridge (1,3)

Complexity: O(V + E).

class Solution:
    def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:
        g = defaultdict(list)
        for a, b in connections:
            g[a].append(b)
            g[b].append(a)
        tin, low, res, timer = [-1] * n, [0] * n, [], [0]

        def dfs(u, parent):
            tin[u] = low[u] = timer[0]
            timer[0] += 1
            for v in g[u]:
                if v == parent:
                    continue
                if tin[v] == -1:
                    dfs(v, u)
                    low[u] = min(low[u], low[v])
                    if low[v] > tin[u]:
                        res.append([u, v])
                else:
                    low[u] = min(low[u], tin[v])

        dfs(0, -1)
        return res