VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kahns-algorithm-in-python/

⇱ Kahn's Algorithm in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kahn's Algorithm in Python

Last Updated : 23 Jul, 2025

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}}
👁 Image

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}}
👁 Image

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.

Step 2: Implementing Kahn's Algorithm

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

Step 3: Putting It All Together

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

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:


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

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

Comment
Article Tags:
Article Tags: