#1192

Critical Connections in a Network

Hard
Depth-First SearchGraph TheoryBiconnected ComponentDepth-First SearchGraph TheoryBiconnected Components
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using Tarjan's algorithm, we can efficiently find critical connections in O(n) time by leveraging depth-first search and tracking discovery and low-link values.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build the graph using an adjacency list.
  2. 2Step 2: Initialize discovery and low arrays, and a parent array to track the DFS tree.
  3. 3Step 3: Perform DFS, updating discovery and low values to identify critical connections.
  4. 4Step 4: If the low value of a neighbor is greater than the discovery value of the current node, it's a critical connection.
solution.py27 lines
1def criticalConnections(n, connections):
2    from collections import defaultdict
3    graph = defaultdict(list)
4    for a, b in connections:
5        graph[a].append(b)
6        graph[b].append(a)
7    discovery = [-1] * n
8    low = [-1] * n
9    parent = [-1] * n
10    critical = []
11    time = [0]
12    def dfs(node):
13        discovery[node] = low[node] = time[0]
14        time[0] += 1
15        for neighbor in graph[node]:
16            if discovery[neighbor] == -1:
17                parent[neighbor] = node
18                dfs(neighbor)
19                low[node] = min(low[node], low[neighbor])
20                if low[neighbor] > discovery[node]:
21                    critical.append([node, neighbor])
22            elif neighbor != parent[node]:
23                low[node] = min(low[node], discovery[neighbor])
24    for i in range(n):
25        if discovery[i] == -1:
26            dfs(i)
27    return critical

Complexity note: The time complexity is O(n) because we visit each node and edge once during the DFS traversal. The space complexity is O(n) due to the storage of the graph and auxiliary arrays.

  • 1Understanding how to track discovery and low values is crucial for identifying critical connections.
  • 2Recognizing the importance of graph traversal techniques like DFS in solving connectivity problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.