Topological sort and dependencies
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Explain what a directed acyclic graph is and why order matters.
- Produce a topological order using indegree and a queue.
- Detect a cycle by checking whether every vertex was emitted.
Overview
#Ordering under constraints
A topological order lists the vertices of a directed graph so that every edge points forward in the list. It exists only when the graph has no directed cycle. Course prerequisites and build dependencies are the classic examples.
Kahn's algorithm
- Compute the indegree of every vertex (how many edges point into it).
- Put every vertex with indegree zero into a queue.
- Repeatedly remove a vertex from the queue, append it to the order, and decrement the indegree of its neighbours. When a neighbour reaches zero, enqueue it.
function topoSort(graph, nodes) {
const indegree = new Map(nodes.map((n) => [n, 0]));
for (const n of nodes) for (const m of graph[n] || []) indegree.set(m, indegree.get(m) + 1);
const queue = nodes.filter((n) => indegree.get(n) === 0);
const order = [];
while (queue.length) {
const n = queue.shift();
order.push(n);
for (const m of graph[n] || []) {
indegree.set(m, indegree.get(m) - 1);
if (indegree.get(m) === 0) queue.push(m);
}
}
return order;
}
Cycle detection
If the emitted order is shorter than the number of vertices, some vertices never reached indegree zero, which means they lie on a directed cycle. That is exactly how a course-scheduling problem reports an impossible plan.
The order is not unique
Several valid topological orders can exist. Kahn's algorithm produces one of them. If a problem asks for the smallest order, replace the queue with a min-heap.
DFS alternative
A depth-first search can also produce a topological order: append a vertex after all its descendants finish, then reverse the result. Both methods are O(vertices + edges).
Practice next
- Return any valid course order or report that no order exists.
- Explain how to find the lexicographically smallest topological order.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
For edges 1 -> 2 and 1 -> 3 with no other edges, which vertices have indegree zero at the start?
starter.javascript// count incoming edges per vertexReveal the reference answer
reference.javascriptVertex 1 has no incoming edges, so its indegree is zero. Vertices 2 and 3 each have one incoming edge. Only 1 starts in the queue.Authored expected output: 1
Sources of the graph are exactly the vertices with indegree zero.
Exercise 2Predict
For the cycle 1 -> 2 -> 3 -> 1, how many vertices does Kahn's algorithm emit?
starter.javascript// every vertex has indegree 1Reveal the reference answer
reference.javascriptEvery vertex has indegree one, so the queue starts empty and no vertex is ever emitted. The order length is 0, which is less than 3, signalling a cycle.Authored expected output: 0
A pure cycle has no source, so topological sort reports failure.
Exercise 3Explain
Explain how to detect a cycle using topological sort.
Reveal the reference answer
reference.textRun Kahn's algorithm and compare the number of emitted vertices with the total number of vertices. If fewer vertices were emitted, the remaining ones are stuck with positive indegree, which means they form or depend on a directed cycle. So a short order is proof of a cycle.Authored expected output: Emitted count less than vertex count means a cycle exists.
This is the standard way scheduling problems report an impossible plan.
Common misconceptions
#- Every directed graph has a topological order. Only acyclic ones do.
- The topological order is unique. Many orders can satisfy the same edges.
- Topological sort sorts by value. It orders by dependency, not by magnitude.
Follow-up practice
#- dsa-from-zero-shortest-paths
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.