DSA · Patterns, not puzzles
How does topological sort work?
Short answer
Topological sort orders the vertices of a directed acyclic graph so every edge points forward. Kahn's algorithm repeatedly removes zero-indegree vertices, while DFS pushes vertices onto a stack after exploring their descendants.
Topological order is only defined for a DAG. If the graph has a cycle, no valid order exists. Common uses are build systems, dependency resolution, course scheduling and task pipelines.
function topologicalSort(graph, nodes) {
const indegree = new Map(nodes.map((node) => [node, 0]));
for (const node of nodes) {
for (const next of graph.get(node) || []) {
indegree.set(next, (indegree.get(next) || 0) + 1);
}
}
const queue = nodes.filter((node) => indegree.get(node) === 0);
let head = 0;
const order = [];
while (head < queue.length) {
const node = queue[head];
head += 1;
order.push(node);
for (const next of graph.get(node) || []) {
indegree.set(next, indegree.get(next) - 1);
if (indegree.get(next) === 0) queue.push(next);
}
}
return order.length === nodes.length ? order : [];
}Kahn's algorithm versus DFS
- Kahn: compute indegrees, process zero-indegree nodes, decrement neighbours
- DFS: recurse into neighbours, then prepend the node to the order
- Kahn detects cycles naturally when fewer than V nodes are processed
- DFS detects cycles with a recursion-path set
- Both run in O(V + E) with an adjacency list
The order is not unique. Any valid sequence that respects every dependency is correct. If a problem requires a specific tie-break, use a heap or sort the zero-indegree set.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How does Kahn's algorithm detect a cycle?
- 2Why is topological order not unique?
- 3How would you produce the lexicographically smallest order?
- 4How do you implement topological sort with DFS?
Say it in the interview
Topological sort orders a DAG so dependencies come before dependents. With Kahn's algorithm I compute indegrees, start with all zero-indegree nodes, and remove edges as I process each node, so processing fewer than all nodes means there is a cycle. The DFS version pushes a node after exploring its neighbours and reverses the result, and both are linear in vertices plus edges.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.