Topological Sort
Order the nodes of a directed acyclic graph so every edge points forward, using Kahn's algorithm or DFS finishing order.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Graph Representation, BFS and DFS
A topological order lists the nodes of a directed acyclic graph (DAG) so that for every edge u -> v, u comes before v. It models dependencies: courses and prerequisites, build systems, task scheduling and spreadsheet recalculation.
Kahn's algorithm (BFS)
- Compute the in-degree of every node.
- Push all nodes with in-degree 0 into a queue.
- Pop a node, append it to the order, and decrement the in-degree of its neighbours; push any that reach 0.
- If the final order has fewer than V nodes, the graph has a cycle.
Using a min-heap instead of a queue gives the lexicographically smallest order.
DFS approach
Run DFS; when a node finishes (all descendants processed), push it to a list. Reversing the list gives a topological order. Detect cycles with the three-colour method.
Beyond ordering
- DP on DAGs: once nodes are in topological order, longest path, number of paths and earliest completion time become simple DP passes.
- Alien Dictionary: build edges from the first differing characters of adjacent words, then topologically sort letters.
- Parallel courses: BFS level count gives the minimum number of semesters.
Pitfall: an order exists only for DAGs. Always check for cycles and handle invalid inputs such as a word followed by its own prefix in Alien Dictionary.
Key concepts
- DAGs and dependency graphs
- Kahn's algorithm with in-degrees
- DFS finishing order
- Cycle detection via topo sort
- DP on DAGs
- Lexicographically smallest order
Mini project
Solve 6 problems: Course Schedule, Course Schedule II, Find Eventual Safe States, Alien Dictionary, Parallel Courses, and Longest Increasing Path in a Matrix (as a DAG).
Check yourself
How does Kahn's algorithm reveal that a directed graph contains a cycle?
Free resources
- Topological sorting (cp-algorithms)
- NeetCode Roadmap (Graphs) (NeetCode)
- CSES Problem Set (Graph Algorithms) (CSES)