⬅ Previous Topic
Topological Sort Using DFSNext Topic ⮕
Cycle Detection in Directed Graph using BFS⬅ Previous Topic
Topological Sort Using DFSNext Topic ⮕
Cycle Detection in Directed Graph using BFSTopic Contents
Topological Sort of a directed graph is a linear ordering of its vertices such that for every directed edge u → v
, vertex u
comes before v
in the ordering.
Kahn’s Algorithm uses a BFS-based approach and is suitable for Directed Acyclic Graphs (DAGs). It efficiently produces a valid topological ordering or detects the presence of a cycle.
u
and add it to the result list.v
of u
:indegree[v]
by 1.indegree[v] == 0
, enqueue v
.null
(cycle detected).function topologicalSortKahn(V, edges) {
const indegree = Array(V).fill(0);
const graph = Array.from({ length: V }, () => []);
const result = [];
for (const [u, v] of edges) {
graph[u].push(v);
indegree[v]++;
}
const queue = [];
for (let i = 0; i < V; i++) {
if (indegree[i] === 0) queue.push(i);
}
while (queue.length) {
const node = queue.shift();
result.push(node);
for (const neighbor of graph[node]) {
indegree[neighbor]--;
if (indegree[neighbor] === 0) queue.push(neighbor);
}
}
return result.length === V ? result : null;
}
const V = 6;
const edges = [[5, 2], [5, 0], [4, 0], [4, 1], [2, 3], [3, 1]];
console.log("Topological Sort:", topologicalSortKahn(V, edges));
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | Even in the best case, we must visit all vertices and all edges once to compute indegrees and process the graph structure. |
Average Case | O(V + E) | For any valid DAG, each vertex and edge is processed exactly once. |
Worst Case | O(V + E) | Regardless of graph structure (as long as it is a DAG), we always have to check every node and every edge at least once. |
O(V + E)
Explanation: We use additional space for the adjacency list (O(E)), indegree array (O(V)), the queue (O(V)), and result list (O(V)).
⬅ Previous Topic
Topological Sort Using DFSNext Topic ⮕
Cycle Detection in Directed Graph using BFSYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.