VOOZH about

URL: https://www.geeksforgeeks.org/dsa/topological-sorting-indegree-based-solution/

⇱ Topological Sorting using BFS - Kahn's Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Topological Sorting using BFS - Kahn's Algorithm

Last Updated : 31 Oct, 2025

Given a Directed Acyclic Graph having V vertices and E edges, find any Topological Sorted ordering of the graph.

Topological Sorted order: It is a linear ordering of vertices such that for every directed edge u -> v, vertex u comes before v in the ordering.

Example:

Input: adj[][] = [[1], [2], [], [2, 4], []]

👁 420046874

Output: [0, 3, 1, 4, 2]
Explanation: For every pair of vertex(u -> v) in the ordering, u comes before v.

Input: adj[][]= [[1], [2], [3], [], [5], [1, 2]]

👁 420046898

Output: [0, 4, 5, 1, 2, 3]
Explanation: For every pair of vertex(u -> v) in the ordering, u comes before v.

[Approach]

The idea is to use Kahn’s Algorithm, which applies BFS to generate a valid topological ordering.
We first compute the in-degree of every vertex — representing how many incoming edges each vertex has. Then, all vertices with an in-degree of 0 are added to a queue, as they can appear first in the ordering.
We repeatedly remove a vertex from the queue, add it to our result list, and reduce the in-degree of all its adjacent vertices. If any of those vertices now have an in-degree of 0, they are added to the queue.
This process continues until the queue is empty, and the resulting order represents one valid topological sort of the graph.

Illustration of the algorithm:


Below is the implementation of the above algorithm. 


Output
0 4 5 1 2 3 

Time Complexity: O(V+E). For Performing BFS
Auxiliary Space: O(V). 

Comment