Compute strongly connected components using Kosaraju's algorithm with two DFS passes: one on the original graph for finish times, one on the transpose graph with reversed edges to find components.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The user is asking me to implement Kosaraju's algorithm for finding strongly connected components (SCCs) in a directed graph. Let me break down the algorithm:
First DFS Pass: Perform DFS on the original graph and record the finish times (push order to stack)
Create Transpose: Create transpose graph (reverse all edges)
Second DFS Pass: Perform DFS on the transpose graph in decreasing order of finish times to identify SCCs
Let me write a comprehensive implementation with:
Clear code structure
Detailed comments
Example usage
Visualization of the process
Time and space complexity analysis
python
from collections import defaultdict, deque
from typing import List, Dict, Set, Tuple
class KosarajuSCC:
"""
Find Strongly Connected Components using Kosaraju's Algorithm
Time Complexity: O(V + E)
Space Complexity: O(V + E)
"""
def __init__(self, num_vertices: int):
"""
Initialize graph with given number of vertices
Args:
num_vertices: Number of vertices in the graph
"""
self.num_vertices = num_vertices
self.graph = defaultdict(list) # Adjacency list
self.finish_stack = [] # Stack to store vertices by finish time
self.visited = set()
def add_edge(self, u: int, v: int):
"""Add a directed edge from u to v"""
self.graph[u].append(v)
def _dfs1(self, vertex: int):
"""
First DFS pass on original graph
Records finish times by pushing to stack
Args:
vertex: Current vertex being visited
"""
self.visited.add(vertex)
# Visit all adjacent vertices
for neighbor in self.graph[vertex]:
if neighbor not in self.visited:
self._dfs1(neighbor)
# Push vertex to stack after visiting all descendants
# Vertices with higher finish times are pushed later
self.finish_stack.append(vertex)
def _get_transpose(self) -> 'defaultdict':
"""
Create transpose graph (reverse all edges)
Returns:
Adjacency list of transpose graph
"""
transpose = defaultdict(list)
for vertex in self.graph:
for neighbor in self.graph[vertex]:
transpose[neighbor].append(vertex)
return transpose
code
def _dfs2(self, vertex: int, transpose: Dict, visited: Set, component: List):
"""
Second DFS pass on transpose graph
Collects vertices in current SCC
Args:
vertex: Current vertex being visited
transpose: Transpose graph adjacency list
visited: Set of visited vertices
component: List to store current SCC
"""
visited.add(vertex)
component.append(vertex)
# Visit all adjacent vertices in transpose graph
for neighbor in transpose[vertex]:
if neighbor not in visited:
self._dfs2(neighbor, transpose, visited, component)
def find_sccs(self) -> List[List[int]]:
"""
Find all Strongly Connected Components
Returns:
List of SCCs, where each SCC is a list of vertices
"""
# Step 1: First DFS pass to get finish times
for vertex in range(self.num_vertices):
if vertex not in self.visited:
self._dfs1(vertex)
# Step 2: Create transpose graph
transpose = self._get_transpose()
# Step 3: Second DFS pass in decreasing order of finish times
visited = set()
sccs = []
# Pop vertices from stack in reverse finish time order to identify components
while self.finish_stack:
vertex = self.finish_stack.pop()
if vertex not in visited:
component = []
self._dfs2(vertex, transpose, visited, component)
sccs.append(component)
return sccs
class KosarajuSCCIterative:
"""
Iterative version of Kosaraju's Algorithm (avoids recursion depth issues)
code
Time Complexity: O(V + E)
Space Complexity: O(V + E)
"""
def __init__(self, num_vertices: int):
self.num_vertices = num_vertices
self.graph = defaultdict(list)
def add_edge(self, u: int, v: int):
"""Add a directed edge from u to v"""
self.graph[u].append(v)
def _dfs1_iterative(self) -> List[int]:
"""
First DFS pass (iterative) to get finish times
Returns:
Stack of vertices ordered by finish time
"""
visited = set()
finish_stack = []
for start in range(self.num_vertices):
if start not in visited:
stack = [(start, 0)] # (vertex, neighbor_index)
while stack:
vertex, idx = stack[-1]
if idx == 0:
visited.add(vertex)
# Explore neighbors, pushing unvisited ones onto stack; when all neighbors processed, record finish time
found_next = False
neighbors = self.graph[vertex]
while idx < len(neighbors):
neighbor = neighbors[idx]
if neighbor not in visited:
stack[-1] = (vertex, idx + 1)
stack.append((neighbor, 0))
found_next = True
break
idx += 1
if not found_next:
finish_stack.append(vertex)
stack.pop()
return finish_stack
def _get_transpose(self) -> defaultdict:
"""Create transpose graph"""
transpose = defaultdict(list)
for vertex in self.graph:
for neighbor in self.graph[vertex]:
transpose[neighbor].append(vertex)
return transpose
def _dfs2_iterative(self, start: int, transpose: defaultdict) -> List[int]:
"""
Second DFS pass (iterative) on transpose graph
Args:
start: Starting vertex
transpose: Transpose graph
Returns:
Vertices in this SCC
"""
visited = {start}
component = [start]
stack = [start]
while stack:
vertex = stack.pop()
for neighbor in transpose[vertex]:
if neighbor not in visited:
visited.add(neighbor)
component.append(neighbor)
stack.append(neighbor)
return component
def find_sccs(self) -> List[List[int]]:
"""Find all Strongly Connected Components"""
finish_stack = self._dfs1_iterative()
transpose = self._get_transpose()
visited = set()
sccs = []
while finish_stack:
vertex = finish_stack.pop()
if vertex not in visited:
component = self._dfs2_iterative(vertex, transpose)
for v in component:
visited.add(v)
sccs.append(sorted(component))
return sccs
def visualize_algorithm(graph: KosarajuSCC, num_vertices: int):
"""
Visualize the step-by-step execution of Kosaraju's algorithm
code
Args:
graph: KosarajuSCC instance
num_vertices: Number of vertices
"""
print("=" * 60)
print("KOSARAJU'S ALGORITHM VISUALIZATION")
print("=" * 60)
print("\n1. ORIGINAL GRAPH:")
for vertex in range(num_vertices):
neighbors = graph.graph[vertex]
if neighbors:
for neighbor in neighbors:
print(f" {vertex} → {neighbor}")
print("\n2. FIRST DFS PASS (Original Graph):")
visited = set()
finish_stack = []
dfs_order = []
def dfs1(v, depth=0):
visited.add(v)
dfs_order.append(v)
print(f" {' ' * depth}Visit {v}")
for neighbor in graph.graph[v]:
if neighbor not in visited:
dfs1(neighbor, depth + 1)
finish_stack.append(v)
print(f" {' ' * depth}Finish {v} (push to stack)")
for vertex in range(num_vertices):
if vertex not in visited:
dfs1(vertex)
print(f"\n Finish Order Stack (top to bottom): {finish_stack[::-1]}")
transpose = graph._get_transpose()
print("\n3. TRANSPOSE GRAPH:")
for vertex in range(num_vertices):
neighbors = transpose[vertex]
if neighbors:
for neighbor in neighbors:
print(f" {vertex} → {neighbor}")
print("\n4. SECOND DFS PASS (Transpose Graph - Reverse Finish Order):")
visited2 = set()
sccs = []
def dfs2(v, component, depth=0):
visited2.add(v)
component.append(v)
print(f" {' ' * depth}Visit {v}")
for neighbor in transpose[v]:
if neighbor not in visited2:
dfs2(neighbor, component, depth + 1)
while finish_stack:
vertex = finish_stack.pop()
if vertex not in visited2:
print(f" Start from {vertex} (highest unvisited finish time)")
component = []
dfs2(vertex, component)
sccs.append(sorted(component))
print(f" → SCC found: {sorted(component)}\n")
print("5. STRONGLY CONNECTED COMPONENTS:")
for i, scc in enumerate(sccs, 1):
print(f" SCC {i}: {scc}")
return sccs
Perform DFS on original graph and push vertices to stack by finish time
Create transpose graph (reverse all edges)
Perform DFS on transpose graph in decreasing order of finish times
Each DFS tree in step 3 is one strongly connected component
Time Complexity: O(V + E) - Two DFS passes
Space Complexity: O(V + E) - Graph storage and recursion stack
Key Insight:
Finish times from original graph help order vertices by "decreasing finish time"
When we traverse transpose in this order, each DFS tree forms an SCC
This works because in transpose, edges between SCCs are reversed
""")
I'm completing the edge list that was cut off and finishing the performance comparison. The implementation includes both recursive and iterative versions of Kosaraju's algorithm, with three example graphs demonstrating different scenarios—a simple cycle, multiple interconnected components, and isolated pairs. The performance comparison measures execution time between the two approaches, and the summary explains the algorithm's core mechanics: using finish times from the first DFS pass to guide traversal of the transposed graph, where each resulting DFS tree represents a strongly connected component.
Kosaraju's Algorithm for Strongly Connected Components
I'll implement a complete solution with two DFS passes, detailed visualization, and both recursive and iterative approaches.
✅ Two DFS passes shown clearly
✅ Finish time ordering explained
✅ Transpose graph creation
✅ Recursive & iterative implementations
✅ Detailed visualization with traces
✅ Time complexity analysis
✅ Multiple examples covering edge cases
from collections import defaultdict, deque
from typing import List, Dict, Set, Tuple
import time
class KosarajuSCC:
"""
Find Strongly Connected Components using Kosaraju's Algorithm
Time Complexity: O(V + E)
Space Complexity: O(V + E)
Algorithm:
1. First DFS: Process original graph, record finish times
2. Create transpose: Reverse all edges
3. Second DFS: Process transpose in decreasing finish time order
"""
def __init__(self, num_vertices: int):
"""Initialize graph with given number of vertices"""
self.num_vertices = num_vertices
self.graph = defaultdict(list) # Adjacency list
self.finish_stack = [] # Stack to store vertices by finish time
self.visited = set()
def add_edge(self, u: int, v: int):
"""Add a directed edge from u to v"""
self.graph[u].append(v)
def _dfs1(self, vertex: int, depth: int = 0):
"""
First DFS pass on original graph.
Records finish times by pushing to stack.
Vertices with higher finish times are processed later in second pass.
"""
self.visited.add(vertex)
print(f"{' ' * depth}→ Visit vertex {vertex} (1st DFS)")
# Visit all adjacent vertices
for neighbor in self.graph[vertex]:
if neighbor not in self.visited:
self._dfs1(neighbor, depth + 1)
# Push to stack when all descendants are processed
# This ensures higher finish times are on top
self.finish_stack.append(vertex)
print(f"{' ' * depth}✓ Finish vertex {vertex} (push to stack)")
def _get_transpose(self) -> defaultdict:
"""Create transpose graph (reverse all edges)"""
transpose = defaultdict(list)
for vertex in range(self.num_vertices):
for neighbor in self.graph[vertex]:
transpose[neighbor].append(vertex)
return transpose
def _dfs2(self, vertex: int, transpose: defaultdict,
visited: Set, component: List, depth: int = 0):
"""
Second DFS pass on transpose graph.
Collects all vertices in current SCC.
"""
visited.add(vertex)
component.append(vertex)
print(f"{' ' * depth}→ Visit vertex {vertex} (2nd DFS)")
# Visit all adjacent vertices in transpose graph
for neighbor in transpose[vertex]:
if neighbor not in visited:
self._dfs2(neighbor, transpose, visited, component, depth + 1)
def find_sccs(self, verbose: bool = False) -> List[List[int]]:
"""Find all Strongly Connected Components"""
print("\n" + "="*60)
print("STEP 1: First DFS Pass (Original Graph)")
print("="*60)
# Step 1: First DFS pass to get finish times
for vertex in range(self.num_vertices):
if vertex not in self.visited:
print(f"\nStarting from vertex {vertex}:")
self._dfs1(vertex)
print(f"\nFinish Stack (top to bottom): {self.finish_stack[::-1]}")
# Step 2: Create transpose graph
print("\n" + "="*60)
print("STEP 2: Create Transpose Graph")
print("="*60)
transpose = self._get_transpose()
self._print_graph("Transpose Graph", transpose)
# Step 3: Second DFS pass in decreasing order of finish times
print("\n" + "="*60)
print("STEP 3: Second DFS Pass (Transpose, Reverse Finish Order)")
print("="*60)
visited = set()
sccs = []
# Pop vertices from stack (highest finish times first)
while self.finish_stack:
vertex = self.finish_stack.pop()
if vertex not in visited:
print(f"\nStarting SCC from vertex {vertex}:")
component = []
self._dfs2(vertex, transpose, visited, component)
sccs.append(sorted(component))
print(f"→ SCC found: {sorted(component)}")
return sccs
def _print_graph(self, title: str, graph: defaultdict):
"""Print graph representation"""
print(f"\n{title}:")
for vertex in range(self.num_vertices):
neighbors = graph[vertex]
if neighbors:
print(f" {vertex} → {neighbors}")
class KosarajuSCCIterative:
"""
Iterative version of Kosaraju's Algorithm.
Avoids potential stack overflow for deep recursion.
"""
def __init__(self, num_vertices: int):
self.num_vertices = num_vertices
self.graph = defaultdict(list)
def add_edge(self, u: int, v: int):
self.graph[u].append(v)
def _dfs1_iterative(self) -> List[int]:
"""First DFS pass (iterative version)"""
visited = set()
finish_stack = []
for start in range(self.num_vertices):
if start in visited:
continue
stack = [start]
path = []
while stack:
vertex = stack[-1]
if vertex not in visited:
visited.add(vertex)
path.append(vertex)
neighbors = self.graph[vertex]
# Add unvisited neighbors to stack
for neighbor in reversed(neighbors):
if neighbor not in visited:
stack.append(neighbor)
else:
stack.pop()
# Add vertices in post-order (finish times)
for v in reversed(path):
if v not in [x for x in finish_stack]:
finish_stack.append(v)
return finish_stack
def _get_transpose(self) -> defaultdict:
"""Create transpose graph"""
transpose = defaultdict(list)
for vertex in range(self.num_vertices):
for neighbor in self.graph[vertex]:
transpose[neighbor].append(vertex)
return transpose
def _dfs2_iterative(self, start: int, transpose: defaultdict,
visited: Set) -> List[int]:
"""Second DFS pass (iterative version)"""
component = []
stack = [start]
visited.add(start)
while stack:
vertex = stack.pop()
component.append(vertex)
for neighbor in transpose[vertex]:
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
return component
def find_sccs(self) -> List[List[int]]:
"""Find all Strongly Connected Components"""
print("\nIterative Kosaraju's Algorithm:")
print("-" * 40)
# Step 1: First DFS to get finish times
finish_stack = self._dfs1_iterative()
print(f"Finish times: {finish_stack}")
# Step 2: Get transpose graph
transpose = self._get_transpose()
# Step 3: Second DFS in reverse finish time order
visited = set()
sccs = []
while finish_stack:
vertex = finish_stack.pop()
if vertex not in visited:
component = self._dfs2_iterative(vertex, transpose, visited)
sccs.append(sorted(component))
return sccs
# ============================================================================
# EXAMPLES AND VISUALIZATION
# ============================================================================
def example1_simple():
"""Example 1: Simple graph with one SCC"""
print("\n" + "█"*60)
print("█ EXAMPLE 1: Simple Graph")
print("█"*60)
graph = KosarajuSCC(5)
edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4)]
print("\nOriginal Graph:")
for u, v in edges:
print(f" {u} → {v}")
graph.add_edge(u, v)
sccs = graph.find_sccs()
print(f"\n{'='*60}")
print("RESULT: Strongly Connected Components")
print(f"{'='*60}")
for i, scc in enumerate(sccs, 1):
print(f"SCC {i}: {scc}")
def example2_complex():
"""Example 2: Multiple SCCs"""
print("\n" + "█"*60)
print("█ EXAMPLE 2: Complex Graph with Multiple SCCs")
print("█"*60)
graph = KosarajuSCC(8)
edges = [
(0, 1), (1, 2), (2, 0), # SCC 1: {0,1,2}
(1, 3), (3, 4), # Path
(4, 5), (5, 6), (6, 4), # SCC 2: {4,5,6}
(6, 7), (7, 8) if 8 < 8 else None # Extended
]
print("\nOriginal Graph:")
for u, v in edges:
if v is not None:
print(f" {u} → {v}")
graph.add_edge(u, v)
sccs = graph.find_sccs()
print(f"\n{'='*60}")
print("RESULT: Strongly Connected Components")
print(f"{'='*60}")
for i, scc in enumerate(sccs, 1):
print(f"SCC {i}: {scc}")
def example3_separate():
"""Example 3: Disconnected SCCs"""
print("\n" + "█"*60)
print("█ EXAMPLE 3: Disconnected Components")
print("█"*60)
graph = KosarajuSCC(6)
edges = [
(0, 1), (1, 0), # SCC 1: {0,1}
(2, 3), (3, 2), # SCC 2: {2,3}
(4, 5), # SCC 3: {4} and {5}
]
print("\nOriginal Graph:")
for u, v in edges:
print(f" {u} → {v}")
graph.add_edge(u, v)
sccs = graph.find_sccs()
print(f"\n{'='*60}")
print("RESULT: Strongly Connected Components")
print(f"{'='*60}")
for i, scc in enumerate(sccs, 1):
print(f"SCC {i}: {scc}")
def example4_iterative():
"""Example 4: Iterative implementation"""
print("\n" + "█"*60)
print("█ EXAMPLE 4: Iterative Implementation")
print("█"*60)
graph = KosarajuSCCIterative(7)
edges = [
(0, 1), (1, 2), (2, 0),
(2, 3), (3, 4),
(4, 5), (5, 4),
(5, 6)
]
print("\nOriginal Graph (Iterative):")
for u, v in edges:
print(f" {u} → {v}")
graph.add_edge(u, v)
sccs = graph.find_sccs()
print(f"\nResult: {sccs}")
def performance_analysis():
"""Analyze time complexity with different graph sizes"""
print("\n" + "█"*60)
print("█ PERFORMANCE ANALYSIS")
print("█"*60)
vertices_list = [100, 500, 1000]
for num_vertices in vertices_list:
graph_rec = KosarajuSCC(num_vertices)
graph_iter = KosarajuSCCIterative(num_vertices)
# Create a chain graph
for i in range(num_vertices - 1):
u, v = i, (i + 1) % num_vertices
graph_rec.add_edge(u, v)
graph_iter.add_edge(u, v)
# Recursive version
start = time.time()
sccs_rec = graph_rec.find_sccs(verbose=False)
time_rec = time.time() - start
# Iterative version
start = time.time()
sccs_iter = graph_iter.find_sccs()
time_iter = time.time() - start
print(f"\nVertices: {num_vertices}")
print(f" Recursive: {time_rec*1000:.3f}ms - {len(sccs_rec)} SCCs")
print(f" Iterative: {time_iter*1000:.3f}ms - {len(sccs_iter)} SCCs")
def algorithm_summary():
"""Print algorithm summary"""
print("\n" + "█"*60)
print("█ KOSARAJU'S ALGORITHM SUMMARY")
print("█"*60)
summary = """
ALGORITHM STEPS:
1. First DFS Pass (Original Graph)
- Process all unvisited vertices
- Record vertices in stack by FINISH TIME
- Vertices finishing later are pushed last (top of stack)
2. Create Transpose Graph
- Reverse direction of all edges
- Key insight: Strongly connected components remain SCCs
- But edges between different SCCs reverse direction
3. Second DFS Pass (Transpose Graph)
- Process vertices in DECREASING order of finish times
- Use them as starting points in transpose
- Each DFS tree is one SCC
WHY IT WORKS:
- Finish times from original graph create an ordering
- In transpose, this ordering ensures we start from vertices
that are "sink" nodes in original graph's SCC DAG
- This allows us to extract one complete SCC per DFS
TIME COMPLEXITY: O(V + E)
- First DFS: O(V + E)
- Transpose creation: O(V + E)
- Second DFS: O(V + E)
- Total: O(V + E)
SPACE COMPLEXITY: O(V + E)
- Graph storage: O(V + E)
- Recursion/Stack: O(V) in worst case
ALTERNATIVE ALGORITHMS:
- Tarjan's Algorithm: O(V + E), single DFS pass
- Path-based algorithm: O(V + E), stack-based
"""
print(summary)
if __name__ == "__main__":
example1_simple()
example2_complex()
example3_separate()
example4_iterative()
performance_analysis()
algorithm_summary()