Topological Sort explained: Kahn’s BFS in-degree algorithm, DFS post-order stack technique, cycle detection, build dependency resolution, and implementation.
Topological Sorting provides a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge u → v, vertex u comes before v in the order. Topological sorting is impossible if the graph contains a cycle.
Common practical applications include build system dependency scheduling (e.g., Make, Webpack), course prerequisite sequencing, and task scheduling.
Compute the in-degree (number of incoming directed edges) for every vertex in the DAG.
Push all vertices with an in-degree of 0 into a processing queue.
Dequeue vertex u, append it to the topological order, and decrement the in-degree of all adjacent vertices v.
If decrementing v’s in-degree brings it to 0, enqueue v. If processed count < total vertices V, the graph contains a cycle!
1// Kahn's Algorithm (BFS-based Topological Sort)2function topologicalSort(numCourses, prerequisites) {3 const inDegree = new Array(numCourses).fill(0);4 const adj = Array.from({ length: numCourses }, () => []);5 6 // Build adjacency list & count in-degrees7 for (const [u, v] of prerequisites) {8 adj[v].push(u); // edge v -> u (v is prerequisite for u)9 inDegree[u]++;10 }11 12 const queue = [];13 for (let i = 0; i < numCourses; i++) {14 if (inDegree[i] === 0) queue.push(i);15 }16 17 const result = [];18 while (queue.length > 0) {19 const node = queue.shift();20 result.push(node);21 22 for (const neighbor of adj[node]) {23 inDegree[neighbor]--;24 if (inDegree[neighbor] === 0) {25 queue.push(neighbor);26 }27 }28 }29 30 // If result length !== numCourses, cycle exists!31 return result.length === numCourses ? result : [];32}Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Interactive node & edge state graph traversal explorer
Test your understanding of Topological Sort (Kahn’s Algorithm & DFS) complexity and step mechanics.
Q1.Which type of graph supports a valid Topological Sort?
Q2.How does Kahn’s algorithm detect a cycle in a directed graph?
Apply Topological Sort (Kahn’s Algorithm & DFS) to real coding interview questions.
Return the ordering of courses you should take to finish all courses given prerequisite pairs.
Derive the alphabetical order of characters in an alien language from a sorted list of words.