Before a compiler can build your program it must sort the source files. Before a course scheduler can enroll you in Advanced Algorithms it must check you've passed Discrete Math. Before npm installs a package it must install that package's own dependencies first. All three problems share a single shape: put things in an order where every prerequisite comes before the thing that needs it.
The mathematical object behind this shape is a directed acyclic graph (DAG) — dots connected by arrows, with no way to follow arrows in a circle back to where you started. Each dot is a task; each arrow says "this must come before that." A topological ordering is any sequence of the dots where every arrow points only forward.
The remarkable fact is that such an ordering can always be found in linear time — , where V is the number of tasks and E the number of dependencies. No backtracking, no guessing, no exponential blowup. The only obstacle is a cycle: if task A depends on B which depends on A, no valid order exists, and the algorithm detects this immediately.
Two classic algorithms find topological orders: Kahn's algorithm (1962), which repeatedly plucks tasks with no remaining prerequisites, and depth-first search (DFS) post-order reversal, which was noted by Knuth and later taught in every algorithms textbook. Both run in time.
Comments
Loading comments...