Kosaraju's Algorithm is a linear-time algorithm used to find all Strongly Connected Components (SCCs) in a directed graph. A sub-graph is strongly connected if there is a path in both directions between every pair of vertices in that sub-graph.
The magic of Kosaraju's algorithm lies in reversing the directions of all edges in the graph:
def kosaraju():
all_nodes = get_all_nodes()
visited = set()
stack = []
# Pass 1: Standard DFS to fill the stack by finish time
def dfs_first_pass(u):
visited.add(u)
for v in neighbors(u):
if v not in visited:
dfs_first_pass(v)
stack.append(u)
for node in all_nodes:
if node not in visited:
dfs_first_pass(node)
# Pass 2: Reverse graph representation
reversed_graph = transpose_edges(all_nodes)
# Pass 3: Process stack on the transposed graph
visited.clear()
scc_count = 0
while len(stack) > 0:
root = stack.pop()
if root not in visited:
scc_count += 1
dfs_second_pass(root, scc_count)
kosaraju()
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | $O(V + E)$ | Where $V$ is the number of vertices and $E$ is the number of edges. We perform two complete DFS traversals and one graph transposition step, all of which run in linear time. |
| Space Complexity | $O(V + E)$ | Space is required for storing the stack ($O(V)$), the recursion tree, and the reversed adjacency list ($O(V + E)$). |