Skip to main content

DFS Topological Sort

Learn DFS Topological Sort (Graphs, Advanced DSA) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

Topological Sort via DFS Finishing Order Run DFS from every unvisited vertex; when a vertex FINISHES (all its descendants fully explored), push it onto a stack. Reversing the finish order (via the stack) gives a valid topological order - a vertex finishes AFTER everything reachable from it, so it naturally ends up appearing BEFORE those descendants once reversed.

More lessons in Graphs