Data Structures Β· Visualization
Graph: Strongly Connected Components (Kosaraju)
Graph
A strongly connected component (SCC) is a maximal set of vertices in a directed graph where every vertex can reach every other. Time: O(V + E). Space: O(V + E) for the transpose graph and visited tracking.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Strongly Connected Components (Kosaraju)
GraphA strongly connected component (SCC) is a maximal set of vertices in a directed graph where every vertex can reach every other. Kosaraju's algorithm finds all SCCs using two depth-first search passes: one on the original graph to order vertices by finish time, one on the transposed (edge-reversed) graph.
How Strongly Connected Components (Kosaraju) Works
- Run DFS on the original graph, pushing each vertex onto a stack when its DFS finishes (post-order).
- Reverse every edge in the graph to build the transpose graph.
- Pop vertices off the stack one at a time; for each unvisited vertex, run DFS on the transpose graph β everything reached in that DFS forms one SCC.
- Repeat until the stack is empty; each DFS call in step 3 discovers exactly one complete SCC.
Strongly Connected Components (Kosaraju) Worked Example
Input: Directed graph: 0β1, 1β2, 2β0, 1β3
- DFS finish order (example): 3, 2, 0, 1 β stack top to bottom: 1,0,2,3
- Transpose edges: 1β0, 2β1, 0β2, 3β1
- Pop 1, DFS on transpose reaches 1,0,2 β SCC {0,1,2}
- Pop 3 (unvisited), DFS reaches just 3 β SCC {3}
Output: Two SCCs found: {0,1,2} and {3}
Press βΆ Run to watch it step by step.
def scc_kosaraju(adj):
n = len(adj)
visited = [False] * n
order = []
def dfs(u, g): # 1st pass: finish order
visited[u] = True
for v in g[u]:
if not visited[v]:
dfs(v, g)
order.append(u)
for u in range(n):
if not visited[u]:
dfs(u, adj)
radj = [[] for _ in range(n)] # reversed graph
for u in range(n):
for v in adj[u]:
radj[v].append(u)
visited = [False] * n
comps = []
for u in reversed(order): # 2nd pass on reversed graph
if not visited[u]:
group = []
dfs(u, radj) # each search = one SCC
for x in reversed(order):
if visited[x] and not any(...): pass
comps.append(group)
return comps
# example: sccBehind the Scenes Execution
Press βΆ Run in the visualizer β the call stack, registers and memory will replay here in sync with the code, line by line.
Strongly Connected Components (Kosaraju) Time & Space Complexity
When to Use Strongly Connected Components (Kosaraju)
- Compiler dependency-cycle detection
- Web page clustering (mutually linked page groups)
- Simplifying a graph into a DAG of components for further analysis
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action β visualize the algorithms that operate on these structures, or take a guided course.