Dependencies as a directed graph
The graph must be a DAG: a directed acyclic graph. If A depends on B while B depends on A, each waits for the other, so no ordering can satisfy both.
Kahn’s algorithm
Kahn’s algorithm tracks each vertex’s in-degree, the number of prerequisites still remaining. Add all zero-in-degree vertices to a queue. Repeatedly remove one, append it to the order, and reduce the in-degree of each dependent vertex. Whenever a count reaches zero, that task is ready to be queued.
Choose Dependency graph in the visualizer and compare Build pipeline or Course prerequisites with Circular dependency. In the cyclic case, some nodes remain after the queue empties. Those nodes belong to or depend on a cycle; the incomplete output signals that no full ordering was found.
Worked example
Suppose the dependencies are A → C, B → C, and C → D. Initially, A and B have in-degree zero. Output A and B in either order; after both edges to C are removed, C becomes ready. Output C, then D. The order preserves every prerequisite edge.
Cost and common mistakes
With adjacency lists, the algorithm takes O(V + E) time and O(V + E) space for the graph and queue. Each vertex is added and removed once, and each edge is processed once.
- Reversing edge direction: choose a convention and keep it consistent; this article uses prerequisite → dependent.
- Assuming there is one answer: independent tasks can appear in multiple valid orders.
- Treating a partial result as complete: fewer output vertices than input vertices means a cycle prevents completion.
- Confusing the queue order with priority: Kahn’s algorithm can use a priority queue to choose among ready tasks when a deterministic or lexicographically smallest order is needed.