1. Count prerequisites
Each incoming edge is one prerequisite for the target node.
indegree[next] += 1Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
Kahn's algorithm: repeatedly emit nodes with zero remaining prerequisites using an indegree count.
A topological order lists nodes so every edge points from earlier to later — only possible on a DAG.
Count each node's indegree, start with the zero-indegree nodes, and emit them one by one.
Emitting a node decrements its neighbors' indegrees; new zeros join the queue.
Indegree = number of prerequisites.
Emit zero-indegree nodes first.
Leftover nodes mean a cycle.
function topoSort(graph, n) {
const indegree = new Array(n).fill(0);
for (let node = 0; node < n; node += 1) {
for (const next of graph[node]) {
indegree[next] += 1;
}
}
const queue = [];
for (let node = 0; node < n; node += 1) {
if (indegree[node] === 0) queue.push(node);
}
const order = [];
while (queue.length > 0) {
const node = queue.shift();
order.push(node);
for (const next of graph[node]) {
indegree[next] -= 1;
if (indegree[next] === 0) queue.push(next);
}
}
return order.length === n ? order : [];
}Connect each part of the code to the concept before you type.
Each incoming edge is one prerequisite for the target node.
indegree[next] += 1Nodes with no prerequisites can go first.
if (indegree[node] === 0) queue.push(node)A dequeued node has all prerequisites satisfied.
order.push(node)Removing a node satisfies one prerequisite of each neighbor.
indegree[next] -= 1If not all nodes emit, a cycle made a valid order impossible.
return order.length === n ? order : []Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputDirected graph · start A · edges A→B:4, A→D:2, B→C:3, B→E:1, D→E:5, E→F:2, C→F:4
Follow temporary values, local state and supporting structures at this step.
queue1 entries
indegrees · nodes A–F6 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state