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:
Kahn’s Algorithm in C++
Next article icon

Kahn's Algorithm in Python

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

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}, {3, 1}, {4, 0}, {4, 1}, {5, 0}, {5, 2}}

Output: 5 4 2 3 1 0
Explanation: In the above output, each dependent vertex is printed after the vertices it depends upon.

Input: V=5 , E={{0, 1}, {1, 2}, {3, 2}, {3, 4}}

Output: 0 3 4 1 2
Explanation: In the above output, each dependent vertex is printed after the vertices it depends upon.

Step-by-Step Implementation:

Step 1: Representing the Graph

We'll represent the graph using an adjacency list. Additionally, we need to keep track of the in-degree (number of incoming edges) of each node.

Python
from collections import defaultdict, deque  class Graph:     def __init__(self, n):         self.n = n         self.graph = defaultdict(list)         self.in_degree = [0] * n          def add_edge(self, u, v):         self.graph[u].append(v)         self.in_degree[v] += 1 

Step 2: Implementing Kahn's Algorithm

The algorithm uses a queue to manage nodes with no incoming edges.

Python
def kahn_topological_sort(graph):     # Queue to hold nodes with no incoming edges     queue = deque([node for node in range(graph.n) if graph.in_degree[node] == 0])          topological_order = []          while queue:         node = queue.popleft()         topological_order.append(node)                  # For each outgoing edge from the current node         for neighbor in graph.graph[node]:             # Decrease the in-degree of the neighbor             graph.in_degree[neighbor] -= 1             # If the neighbor has no other incoming edges, add it to the queue             if graph.in_degree[neighbor] == 0:                 queue.append(neighbor)          # Check if topological sorting is possible (graph should have no cycles)     if len(topological_order) == graph.n:         return topological_order     else:         # If not all nodes are in topological order, there is a cycle         return "Graph has at least one cycle" 

Step 3: Putting It All Together

Now we can combine the graph creation and Kahn's Algorithm into a complete example.

Python
# Example usage def main():     # Number of nodes in the graph     n = 6     # List of edges in the graph     edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]          # Create a graph with n nodes     graph = Graph(n)          # Add edges to the graph     for u, v in edges:         graph.add_edge(u, v)          # Perform topological sort using Kahn's Algorithm     topological_order = kahn_topological_sort(graph)          print("Topological Order:", topological_order)  if __name__ == "__main__":     main() 

Explanation:

  1. Graph Representation: The graph is represented using an adjacency list, and the in-degree of each node is tracked.
  2. Queue Initialization: Nodes with no incoming edges are added to the queue initially.
  3. Topological Sorting: Nodes are processed in the order they are dequeued. For each node, its neighbors' in-degrees are reduced by 1. If a neighbor's in-degree becomes 0, it is added to the queue.
  4. Cycle Detection: After processing all nodes, if the topological order contains all nodes, the graph is a DAG. Otherwise, the graph contains at least one cycle.

Python Implementation:

Here is the complete code for Kahn's Algorithm in Python:

Python
from collections import defaultdict, deque  class Graph:     def __init__(self, n):         self.n = n         self.graph = defaultdict(list)         self.in_degree = [0] * n          def add_edge(self, u, v):         self.graph[u].append(v)         self.in_degree[v] += 1  def kahn_topological_sort(graph):     # Queue to hold nodes with no incoming edges     queue = deque([node for node in range(graph.n) if graph.in_degree[node] == 0])          topological_order = []          while queue:         node = queue.popleft()         topological_order.append(node)                  # For each outgoing edge from the current node         for neighbor in graph.graph[node]:             # Decrease the in-degree of the neighbor             graph.in_degree[neighbor] -= 1             # If the neighbor has no other incoming edges, add it to the queue             if graph.in_degree[neighbor] == 0:                 queue.append(neighbor)          # Check if topological sorting is possible (graph should have no cycles)     if len(topological_order) == graph.n:         return topological_order     else:         # If not all nodes are in topological order, there is a cycle         return "Graph has at least one cycle"  # Example usage def main():     # Number of nodes in the graph     n = 6     # List of edges in the graph     edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]          # Create a graph with n nodes     graph = Graph(n)          # Add edges to the graph     for u, v in edges:         graph.add_edge(u, v)          # Perform topological sort using Kahn's Algorithm     topological_order = kahn_topological_sort(graph)          print("Topological Order:", topological_order)  if __name__ == "__main__":     main() 

Output
Topological Order: [4, 5, 2, 0, 3, 1] 

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Kahn’s Algorithm in C++

C

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

Similar Reads

  • 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 Python
    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 effic
    3 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
  • 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
  • A* Search Algorithm in Python
    Given an adjacency list and a heuristic function for a directed graph, implement the A* search algorithm to find the shortest path from a start node to a goal node. Examples: Input:Start Node: AGoal Node: FNodes: A, B, C, D, E, FEdges with weights:(A, B, 1), (A, C, 4),(B, D, 3), (B, E, 5),(C, F, 2),
    8 min read
  • Searching Algorithms in Python
    Searching algorithms are fundamental techniques used to find an element or a value within a collection of data. In this tutorial, we'll explore some of the most commonly used searching algorithms in Python. These algorithms include Linear Search, Binary Search, Interpolation Search, and Jump Search.
    6 min read
  • Kahn’s Algorithm in C Language
    In this post, we will see the implementation of Kahn's Algorithm in C language. What is Kahn's Algorithm?The Kahn's Algorithm is a classic algorithm used to the perform the topological sorting on the Directed Acyclic Graph (DAG). It produces a linear ordering of the vertices such that for every dire
    5 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
  • Bitwise Algorithm in Python
    Bitwise algorithms refer to the use of bitwise operators to manipulate individual bits of data. Python provides a set of bitwise operators such as AND (&), OR (|), XOR (^), NOT (~), shift left (<<), and shift right (>>). These operators are commonly used in tasks like encryption, com
    6 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