Learn topological sorting on Directed Acyclic Graphs (DAGs) using Kahn's in-degree algorithm for build systems and task ordering.
Learn how dynamic arrays achieve O(1) amortized insertion, contiguous memory layout, and geometric doubling strategies.
A Topological Sort of a Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge $u o v$, vertex $u$ comes before vertex $v$ in the ordering.
Topological sort resolves dependencies in package managers (npm, pnpm), build systems (Webpack, Vite), and college course prerequisites.
Course Dependencies: [ Math 101 ] ──► [ Calculus ] ──► [ Machine Learning ]
[ CS 101 ] ──► [ Data Structures ] ──┘
Valid Topological Order: [ Math 101, CS 101, Calculus, Data Structures, Machine Learning ]
inDegree === 0 (nodes with no prerequisites).0, enqueue it!function topologicalSort(numCourses, prerequisites) {
const inDegree = new Array(numCourses).fill(0);
const adjList = new Map();
for (let i = 0; i < numCourses; i++) adjList.set(i, []);
for (const [course, prereq] of prerequisites) {
adjList.get(prereq).push(course);
inDegree[course]++;
}
const queue = [];
for (let i = 0; i < numCourses; i++) {
if (inDegree[i] === 0) queue.push(i);
}
const order = [];
while (queue.length > 0) {
const curr = queue.shift();
order.push(curr);
for (const neighbor of adjList.get(curr)) {
inDegree[neighbor]--;
if (inDegree[neighbor] === 0) {
queue.push(neighbor);
}
}
}
// If order contains all courses, no cycle exists!
return order.length === numCourses ? order : [];
}
console.log(topologicalSort(4, [[1, 0], [2, 0], [3, 1], [3, 2]]));
// Output: [0, 1, 2, 3] or [0, 2, 1, 3]
If the graph contains a directed cycle (e.g. $A o B o A$), order.length < numCourses because nodes in the cycle never reach inDegree === 0.
order.length === totalVertices to detect cycles.Use Kahn's algorithm for compilation task scheduling. Next, let's explore Dijkstra's Shortest Path Algorithm!