Prerequisites
Exams, courses or tasks requiring earlier results.
Algorithms · Directed graphs
If an edge u→v means “u must come before v”, a topological ordering places every vertex in a sequence that respects every dependency.
Definition. Given a directed graph G = (V, E), a topological ordering is a permutation of the vertices such that, for every edge (u, v) ∈ E, u appears before v.
A→C→D→F
The order describes constraints, not necessarily a unique timeline. If A and B are unrelated by any path, they can often swap places without invalidating the result.
Exams, courses or tasks requiring earlier results.
Build a dependency before the module that imports it.
Find a feasible order; durations require further techniques.
A DAG is a directed acyclic graph. If A→B→C→A is a cycle, each vertex would have to precede itself, an impossible constraint. Conversely, every DAG contains at least one vertex with in-degree zero.
Advance one operation at a time: node badges show residual in-degree, while dashed edges have already been removed.
—
A zero-in-degree vertex has no predecessor left to place, so it may safely be the next element.
The output sequence respects every removed edge, and stored in-degrees exactly match the residual graph.
If the queue empties while vertices remain, each has a residual predecessor. Following them in a finite set must eventually repeat a vertex, proving a cycle.
| Operation | Cost | Reason |
|---|---|---|
| Compute in-degrees | Θ(|V| + |E|) | Initialize vertices and scan all edges once. |
| Queue and removals | Θ(|V| + |E|) | Each vertex is enqueued once; each edge causes one decrement. |
| Total time | Θ(|V| + |E|) | With adjacency lists. |
| Auxiliary space | Θ(|V|) | In-degrees, queue and output; the graph itself takes Θ(|V| + |E|). |
DFS can colour vertices white, grey and black: an edge to a grey vertex reveals a cycle; if none exists, reverse finishing order is topological. It has the same Θ(|V| + |E|) cost, while Kahn makes available prerequisites and parallelism more explicit.
Before running the diamond, list every valid ordering.
Add F>B to the initial dependencies: when does Kahn detect the cycle?
How would you change the queue to always obtain the lexicographically smallest order?