Intervue featured on Shark TankIntervue featured on Shark Tank - mobile banner

Critical Connections

In a given graph, a critical connection is an edge that, when removed, increases the number of connected components in the graph. Given a graph with n nodes and edges, find all critical connections.

Constraints:

  • 1 <= n <= 10^4
  • 0 <= edges.length <= 10^4
  • edges[i].length == 2
  • 0 <= edges[i][0] < n
  • 0 <= edges[i][1] < n
  • edges[i][0] != edges[i][1]

Examples:

Input: [[0,1],[1,2],[2,0],[1,3]]

Output: [[1,3]]

Explanation: The edge between nodes 1 and 3 is a critical connection because removing it increases the number of connected components in the graph.

Solutions

Tarjan's Algorithm

Time: O(n + m)Space: O(n + m)

Tarjan's algorithm is used to find all critical connections in the graph. The algorithm works by performing a depth-first search (DFS) on the graph and keeping track of the discovery time and low value for each node. The low value of a node is the smallest discovery time of any node that is reachable from the current node. If the low value of a node is greater than the discovery time of its parent, then the edge between the node and its parent is a critical connection.


def criticalConnections(n, edges):
    graph = [[] for _ in range(n)] for u, v in edges:
        graph[u].append(v) graph[v].append(u) low = [0] * n disc = [0] * n time = 0 result = []
        def dfs(node, parent):
            nonlocal time disc[node] = low[node] = time time += 1 for neighbor in graph[node]:
                if disc[neighbor] == 0:
                    dfs(neighbor, node) low[node] = min(low[node], low[neighbor]) if low[neighbor] > disc[node]:
                        result.append([node, neighbor]) elif neighbor != parent:
                            low[node] = min(low[node], disc[neighbor]) for i in range(n):
                                if disc[i] == 0:
                                    dfs(i, -1) return result

Difficulty: Hard

Category: Graph

Frequency: High

Company tags:

GoogleAmazonFacebook