⬅ Previous Topic
Check if a Graph is Bipartite using DFSNext Topic ⮕
Topological Sort using Kahn's Algorithm⬅ Previous Topic
Check if a Graph is Bipartite using DFSNext Topic ⮕
Topological Sort using Kahn's AlgorithmTopic Contents
Topological Sort is a linear ordering of vertices in a directed graph such that for every directed edge u → v
, vertex u
comes before v
in the ordering.
It is only applicable to Directed Acyclic Graphs (DAGs) and is used in scenarios like task scheduling, build systems, and dependency resolution.
visited
set and a stack
(for order).dfs(node)
:
node
as visited.neighbor
of node
:
dfs(neighbor)
.node
to stack
.dfs
on all unvisited nodes.stack
to get the topological order.function topologicalSort(graph) {
const visited = new Set();
const stack = [];
function dfs(node) {
visited.add(node);
for (const neighbor of graph[node] || []) {
if (!visited.has(neighbor)) {
dfs(neighbor);
}
}
stack.push(node);
}
for (const node in graph) {
if (!visited.has(Number(node))) {
dfs(Number(node));
}
}
return stack.reverse();
}
const graph = {
5: [0, 2],
4: [0, 1],
2: [3],
3: [1],
0: [],
1: []
};
console.log("Topological Sort:", topologicalSort(graph));
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(V + E) | Even in the best case, each vertex and its edges must be visited to ensure proper order. |
Average Case | O(V + E) | Every node is visited once and all its outgoing edges are checked once during DFS. |
Worst Case | O(V + E) | In the worst case, the graph is dense, and all vertices and edges must be processed. |
O(V + E)
Explanation: We use a visited set (O(V)), a stack (O(V)), and an adjacency list (O(V + E)) to represent the graph.
⬅ Previous Topic
Check if a Graph is Bipartite using DFSNext Topic ⮕
Topological Sort using Kahn's AlgorithmYou 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.