7.4 Topological Sort & Weighted DAG Shortest Paths
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: Morning Dressing & College Prerequisitesβ
You cannot put on boots before socks, or zip a coat before putting on a shirt. A Topological Sort arranges dependency arrows (u -> v) into one flat assembly line so every prerequisite completes strictly to the left of any downstream task β and if a circular dependency exists (A needs B, B needs A), no valid order exists at all!
π» Bridging to Computer Science:β
Any Directed Acyclic Graph (DAG) guarantees at least one valid linear ordering via two engines: DFS Reverse Finish-Time Prepending and Kahn's BFS Zero-In-Degree Peeling. Once topologically sorted, even weighted DAG shortest paths (supporting negative weights!) resolve in one linear sweep!
πTable of Contents
- π Method 1: DFS Reverse Finishing-Time Linked List
- π Method 2: Kahn's BFS Zero-In-Degree Algorithm (Cycle-Aware)
- β‘ Weighted DAG Single-Source Shortest Path in Linear Time
- π Real-World Production Context: Build Orchestrators & Critical Paths
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π Method 1: DFS Reverse Finishing-Time Linked Listβ
Run DFS across all graph components; at the exact instant vertex turns BLACK (all outgoing edges unwound, finishing time f[u]), prepend to the front of a singly linked list:
π Method 2: Kahn's BFS Zero-In-Degree Algorithm (Cycle-Aware)β
Kahn's iterative Queue algorithm peels off nodes whose prerequisites are completely satisfied (inDegree == 0):
- Compute
inDegree[v]for all vertices; enqueue every vertex withinDegree[v] == 0. - Pop
u, appenduto result array, decrementinDegree[nbr]on each outgoing edge, and enqueue any neighbor hitting0. - Built-In Cycle Check: If
output.length < V, leftover stuck nodes contain a directed cycle (zero topological ordering possible)!
β‘ Weighted DAG Single-Source Shortest Path in Linear Timeβ
Once vertices sit in Topological Order [v1, v2, ..., vn], no path can ever flow backward! Stepping once left-to-right and relaxing outgoing edges computes exact shortest paths even with negative edge weights in β outperforming both Dijkstra () and Bellman-Ford ()!
π Real-World Production Context: Build Orchestrators & Critical Pathsβ
Topological Orderings Across Engineering Pipelines
Dependency DAG scheduling drives parallel compilation, spreadsheet recalculation, and critical path analysis
Parallel Build Systems & Package Resolvers
Bazel / Nix / Cargo- Kahn's Queue executes every inDegree == 0 library compilation simultaneously across multi-core build workers.
- Reports instant cyclic-import errors whenever outputCount < numPackages.
Spreadsheet Formulas & React Recalc Graphs
Excel / Build DAGs- Evaluates upstream cells cleanly before formulas referencing them so no cell recomputes twice.
- Detects #CIRCULAR_REF errors instantly before evaluation.
PERT Critical Path & Negative-Weight DAGs
O(V + E) Relaxation- Linear topological relaxation solves longest critical paths (by negating weights) without exponential search.
- Beats Bellman-Ford by a factor of O(V) on acyclic workflows.
π Numerical Applications & Worked Examplesβ
- Consider a -vertex DAG with and strictly two prerequisite constraints:
A -> CandB -> D(with zero edges linking and ). Calculate the exact count of distinct valid Topological Orderings. - Suppose Kahn's BFS runs on a -vertex directed graph, processes
Node 1, thenNode 2, and stops cleanly with Queue empty whileinDegree[3]=1, inDegree[4]=1, inDegree[5]=1. What does that prove?
Step-by-Step Solution:β
-
Valid Ordering Count: Total permutations . Independent constraints
A before C() andB before D(): -
Kahn's Early Queue Empty Interpretation: Because nodes popped before Queue hit empty, remaining vertices
{3, 4, 5}mutually block each other's prerequisites{3, 4, 5}strictly contains a Directed Cycle!
π― Exam & Interview Pitfall Checkβ
- When does a DAG possess strictly ONE unique Topological Ordering?
- If and only if the DAG contains a Hamiltonian Directed Path (
v1 -> v2 -> ... -> vn) connecting consecutive positions! (In Kahn's algorithm, queue size stays strictly at every step!)
- If and only if the DAG contains a Hamiltonian Directed Path (
- Can a Topological Ordering exist if a directed graph contains even 1 self-loop
u -> u?- No! Any self-loop breaks acyclicity (
inDegree[u] >= 1permanently), so neither DFS nor Kahn can produce a valid topological order.
- No! Any self-loop breaks acyclicity (
- Running DFS Finish-Time Topo Sort Without Detecting Cycles First: DFS still blindly outputs a permutation of vertices even when cycles exist! Always combine Kahn's
visited == Vcounter OR check forGRAYBack Edges before trusting DFS output as a valid topological sort! - Using Dijkstra Instead of Topological Relaxation on Dense Negative-Edge DAGs: Dijkstra fails on negative edges; if the graph is acyclic (
DAG), single-pass topological relaxation handles arbitrary negative weights cleanly in !
π Navigation & Next Stepsβ
Next, we step from directed dependency chains into undirected network resilience: Topic 7.5 β Articulation Points (Cut Vertices), Bridges & Biconnected Graphs.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.