Topological sort

hip-hop, educational

Listen on 93

Lyrics

[Verse 1]
Directed graph sprawled before me, nodes scattered wild
Dependencies tangled tight like circuits gone riled
Need an ordering that respects each connection
Zero indegree vertices catch my attention

Start with nodes that have no arrows pointing in
Queue them up, let the sorting begin
Remove each vertex, decrease neighbor counts
Watch the cascade as the algorithm mounts

[Chorus]
Topo sort, topo sort, DAG required first
In-degree zero, that's where we immerse
Kahn's algorithm or DFS post-order time
Linear arrangement where dependencies rhyme

No cycles allowed or the whole thing breaks
Partial order to total, whatever it takes
Topo sort, topo sort, prerequisites align
Build systems compile when the sequence is fine

[Verse 2]
DFS traversal diving deep through the maze
Mark each node when recursion delays
Post-order numbering as we backtrack home
Reverse that list and watch the pattern roam

Finishing times tell the ordering tale
Later finish means earlier in the trail
Stack unwinding reveals the hidden sequence
Dependencies honored with mathematical sequence

[Chorus]
Topo sort, topo sort, DAG required first
In-degree zero, that's where we immerse
Kahn's algorithm or DFS post-order time
Linear arrangement where dependencies rhyme

No cycles allowed or the whole thing breaks
Partial order to total, whatever it takes
Topo sort, topo sort, prerequisites align
Build systems compile when the sequence is fine

[Bridge]
Course scheduling needs this foundation
Job dependencies across the nation
Makefile targets in compilation chains
Spreadsheet formulas breaking their reins

Two algorithms serve the same goal
Kahn's with queues, DFS with soul
Both produce valid orderings true
Multiple answers when choices accrue

[Outro]
When arrows point forward in time's direction
Topological sort grants perfect selection
Linear sequence from partial constraint
DAG transforms to orderedaint

← A* search | Tarjan's algorithm (strongly connected components) →