Quick Notes #1: Kahn’s Algorithm

Alok Ratnaparkhi
1 min readDec 29, 2020

Topological ordering is an important concept in graph theory. Topological ordering is a linear ordering of vertices of the directed acyclic graph such that for every edge from u to v, u comes before v in the ordering.

Practical applications of topological ordering:

  1. Dependency Management
  2. Package/Libraries Management
  3. Task Scheduling
  4. Finding Cycles in a graph

Note that, topological order does not exist for an undirected or cyclic graph.

There are several ways to find the topological ordering of a DAG. The standard way is to traverse the graph using DFS or BFS and add the visited notes into the stack.

Standard Implementation: https://github.com/AlokRatnaparkhi/LeetCodePractice/blob/master/Leetcode/src/TopologicalSort.java

Alternatively, there is an elegant and simple way to find the topological graph. The way is known as Kahn’s Algorithm.

Resources:

Psuedo code:

def findTopologicalOrder(Graph g){

Let indegree[] be the array to store indegrees of vertices

Let order[] be the array to store topological order

for all vertices in Graph G

{ calculate the indegrees of all vertices in G by looping through adjacency list

}

Find nodes with 0 indegree and add them to Queue

while queue is not empty{

int u=queue.pop();

order.add(u);

for all neighbors of u{

decrement the indegrees of u;

if(indegree[u]==0) add u to the queue;

}

if(order.length==number of vertices in the graph)

{return order;

}

else

{ return null; //Cycle exist in a graph

}

}

Source code (Java):

Time Complexity:

O(V+E)

Space complexity:

O(V)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Alok Ratnaparkhi
Alok Ratnaparkhi

Written by Alok Ratnaparkhi

Algorithms |AI | Machine learning

No responses yet

Write a response