Skip to main content

Kahn's Algorithm

1. What is Kahn's Algorithm?​

Kahn's Algorithm is an algorithm for topological sorting of a directed acyclic graph (DAG). It uses an iterative approach to remove nodes with no incoming edges and forms a topological order of the vertices.

2. Algorithm for Kahn's Algorithm​

  1. Initialize In-Degree: Compute the in-degree (number of incoming edges) for each vertex.
  2. Initialize Queue: Collect all vertices with an in-degree of 0 in a queue.
  3. Process Vertices:
    • Remove a vertex from the queue and add it to the topological order.
    • Decrease the in-degree of all its neighboring vertices by 1.
    • If any neighboring vertex's in-degree becomes 0, add it to the queue.
  4. Check for Cycles: If the number of vertices in the topological order is less than the total number of vertices, the graph has a cycle.

3. How Does Kahn's Algorithm Work?​

  • In-Degree Calculation: Helps identify vertices with no dependencies (in-degree 0).
  • Queue Processing: Ensures vertices are processed in the order of their dependencies being resolved.
  • Cycle Detection: If all vertices are not included in the topological order, the graph contains a cycle.

4. Problem Description​

Given a directed acyclic graph (DAG), perform a topological sort of its vertices.

5. Examples​

Example graph:

      5 β†’ 0 ← 4
↓ ↓
2 β†’ 3 β†’ 1

Topological Sort: 4, 5, 0, 2, 3, 1 or 5, 4, 2, 3, 0, 1 (one of the valid topological orders)

6. Constraints​

  • The graph must be directed and acyclic.

7. Implementation​

Kahn's Algorithm​

from collections import deque, defaultdict

def kahns_algorithm(graph):
in_degree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
in_degree[v] += 1

queue = deque([u for u in graph if in_degree[u] == 0])
topo_order = []

while queue:
u = queue.popleft()
topo_order.append(u)

for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)

if len(topo_order) == len(graph):
return topo_order
else:
return [] # The graph has a cycle

graph = {
5: [0, 2],
4: [0, 1],
2: [3],
3: [1],
1: [],
0: []
}

print(kahns_algorithm(graph))

8. Complexity Analysis​

  • Time Complexity: O(V+E)O(V + E) where VV is the number of vertices and EE is the number of edges.
  • Space Complexity: O(V)O(V) due to the storage required for the in-degree array and the queue.

9. Advantages and Disadvantages​

Advantages:​

  • Efficient and straightforward for DAGs.
  • Useful for scheduling tasks, resolving symbol dependencies in linkers, etc.

Disadvantages:​

  • Only applicable to directed acyclic graphs (DAGs).
  • Does not handle graphs with cycles.

10. References​