Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Kosaraju’s Algorithm in C
Next article icon

Kosaraju's Algorithm in Python

Last Updated : 30 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

What is Kosaraju's Algorithm?

Kosaraju's Algorithm is a classic graph theory algorithm used to find the Strongly Connected Components (SCCs) in a directed graph. A strongly connected component is a maximal subgraph where every vertex is reachable from every other vertex. Kosaraju's algorithm is efficient, with a time complexity of O(V+E), where V is the number of vertices and E is the number of edges.

Kosaraju's algorithm consists of two main passes over the graph:

  1. First Pass: Perform a Depth-First Search (DFS) on the original graph to compute the finishing times of the vertices.
  2. Second Pass: Perform a DFS on the transposed graph (graph with all edges reversed) in the order of decreasing finishing times obtained in the first pass.

The algorithm can be broken down into the following steps:

Steps of Kosaraju's Algorithm:

  1. Initialize: Create an empty stack to store the order of finishing times and a visited list to track visited vertices.
  2. First DFS: Perform DFS on the original graph. Push each vertex onto the stack once its DFS finishes.
  3. Transpose Graph: Reverse the direction of all edges in the graph to get the transposed graph.
  4. Second DFS: Perform DFS on the transposed graph using the vertices in the order defined by the stack (from the first DFS).
  5. Collect SCCs: Each DFS in this second pass gives one SCC.

Implementation of Kosaraju's Algorithm in Python

Here’s a Python implementation of Kosaraju’s Algorithm:

Python
from collections import defaultdict, deque  class Graph:     def __init__(self, vertices):         self.V = vertices         self.graph = defaultdict(list)      def add_edge(self, u, v):         self.graph[u].append(v)      def _dfs(self, v, visited, stack):         visited[v] = True         for neighbor in self.graph[v]:             if not visited[neighbor]:                 self._dfs(neighbor, visited, stack)         stack.append(v)      def _transpose(self):         transposed_graph = Graph(self.V)         for node in self.graph:             for neighbor in self.graph[node]:                 transposed_graph.add_edge(neighbor, node)         return transposed_graph      def _fill_order(self, visited, stack):         for i in range(self.V):             if not visited[i]:                 self._dfs(i, visited, stack)      def _dfs_util(self, v, visited, component):         visited[v] = True         component.append(v)         for neighbor in self.graph[v]:             if not visited[neighbor]:                 self._dfs_util(neighbor, visited, component)      def kosaraju_scc(self):         stack = deque()         visited = [False] * self.V          self._fill_order(visited, stack)          transposed_graph = self._transpose()          visited = [False] * self.V         scc_list = []          while stack:             node = stack.pop()             if not visited[node]:                 component = []                 transposed_graph._dfs_util(node, visited, component)                 scc_list.append(component)          return scc_list  # Example usage if __name__ == "__main__":     g = Graph(5)     g.add_edge(1, 0)     g.add_edge(0, 2)     g.add_edge(2, 1)     g.add_edge(0, 3)     g.add_edge(3, 4)      sccs = g.kosaraju_scc()     print("Strongly Connected Components:", sccs) 

Output
Strongly Connected Components: [[0, 1, 2], [3], [4]] 

Time complexity: O(V+E), where V is the number of vertices and E is the number of edges in the graph.
Auxiliary space: O(V+E)


Next Article
Kosaraju’s Algorithm in C

C

code_r
Improve
Article Tags :
  • Graph
  • DSA
  • Python-DSA
Practice Tags :
  • Graph

Similar Reads

  • Kahn's Algorithm in Python
    Kahn's Algorithm is used for topological sorting of a directed acyclic graph (DAG). The algorithm works by repeatedly removing nodes with no incoming edges and recording them in a topological order. Here's a step-by-step implementation of Kahn's Algorithm in Python. Example: Input: V=6 , E = {{2, 3}
    4 min read
  • Karatsuba Algorithm in Python
    Karatsuba Algorithm is a fast multiplication algorithm that efficiently multiplies large numbers by recursively breaking them down into smaller parts. Examples: Input: A = 5678 B = 1234Output: 7006652 Input: A = 1456 B = 6533Output: 9512048 Using the Naive approach, we can multiply two numeric strin
    4 min read
  • Kruskal's Algorithm in Python
    Kruskal’s Algorithm is a greedy algorithm used to find MST in the graph. A minimum spanning tree (MST) is a spanning tree with a weight less than or equal to the weight of every other spanning tree. Kruskal’s Algorithm sorts all edges of the given graph in increasing order. Then it keeps on adding n
    4 min read
  • Kosaraju’s Algorithm in C
    Kosaraju’s Algorithm is a method by which we can use to find all strongly connected components (SCCs) in a directed graph. This algorithm has application in various applications such as finding cycles in a graph, understanding the structure of the web, and analyzing networks. In this article, we wil
    5 min read
  • Kosaraju’s Algorithm in C++
    In this post, we will see the implementation of Kosaraju’s Algorithm in C++. What is Kosaraju’s Algorithm?Kosaraju’s Algorithm is a classic algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every oth
    4 min read
  • Prim's Algorithm in Python
    Prim's algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, undirected graph. The MST is a subset of the edges that connects all vertices in the graph with the minimum possible total edge weight. The algorithm starts with an empty spanning tree.The idea is to
    5 min read
  • Dial's Algorithm in Python
    Dial's algorithm is a graph algorithm used for the finding the shortest path in a graph with the non-negative edge weights. It is an optimization of the Dijkstra's algorithm and is particularly efficient for the graphs with the bounded range of the edge weights. What is Dial's Algorithm?The Dial's a
    4 min read
  • Kahn’s Algorithm in C++
    In this post, we will see the implementation of Kahn’s Algorithm in C++. What is Kahn’s Algorithm?Kahn’s Algorithm is a classic algorithm used for topological sorting of a directed acyclic graph (DAG). Topological sorting is a linear ordering of vertices such that for every directed edge u -> v,
    4 min read
  • Hopcroft–Karp Algorithm in Python
    A matching in a Bipartite Graph is a set of edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum ma
    5 min read
  • Strassen algorithm in Python
    Strassen's algorithm is an efficient method for matrix multiplication. It reduces the number of arithmetic operations required for multiplying two matrices by decomposing them into smaller submatrices and performing recursive multiplication. Strassen's algorithm is based on the divide-and-conquer ap
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences