Topological Sort / DAG
Order directed acyclic graph nodes so every prerequisite appears before the work that depends on it.
The task has prerequisites, dependencies, course ordering, or asks whether a directed graph has a cycle.
How to approach it
Count incoming edges, queue zero-indegree nodes, and decrement neighbors. If fewer than all nodes are processed, a cycle exists.
A topological order exists only for a DAG and may not be unique.
Practice question
Give one valid order for tasks A, B, C, D with dependencies A→C, B→C, C→D.
A and B must precede C; C must precede D.Give your answer before revealing the explanation.Show a hint
Start with any task that has no prerequisites.
Show an answer
A, B, C, D (B, A, C, D is also valid).
Topological Sort / DAG at work
A release has tasks: compile before test, test before package, and compile before documentation. Give a valid order that respects these dependencies.
Show one possible approach
Compile, then test and documentation in either order, then package. A topological ordering places each prerequisite before its dependents.
Practice next
Use these problem IDs to find additional practice for this pattern: