CSAlgorithms & ComplexityDiagramIntermediate
Topological Sort
KO: 위상 정렬·EN: Topological Sort·JA: トポロジカルソート
An O(V+E) linear ordering of vertices in a Directed Acyclic Graph (DAG) such that every dependency edge u → v places u before v
Table of Contents
Structure Diagram
Topological Sort DAG Dependency OrderingTap a node
ROOT1. core-lib (in=0)
2 linksQuick Answer
What is Topological Sort?
An O(V+E) linear ordering of vertices in a Directed Acyclic Graph (DAG) such that every dependency edge u → v places u before v. It is a core concept in Algorithms & Complexity within CS.
Core Principles
Topological Sort produces a linear execution order for a Directed Acyclic Graph (DAG) so that for every directed edge u → v, u always appears before v.
- Kahn's Algorithm (BFS): Enqueue all vertices with
in-degree == 0, pop them one by one, and decrement neighbors' in-degrees. - DFS Post-Order: Append each vertex after visiting all its descendants, then reverse the list.
- Built-in Cycle Detection: If fewer than
Vnodes are emitted, the graph contains a cycle and no valid ordering exists. Runs inO(V + E).
Practical Takeaways
- Parallel execution levels: Nodes reaching
in-degree == 0in the same wave of Kahn's algorithm have no mutual dependencies and can run concurrently. - Detecting circular dependencies: Package managers and DI containers use topological sort failures to surface circular import chains.
- Deterministic tie-breaking: Replace the FIFO queue with a min-heap whenever you need a canonical lexicographical order.
Notable Examples
- Build Tools & Package Managers: Bazel, Turborepo, Make, and npm resolving build order.
- Data Orchestrators: Apache Airflow and dbt executing DAG workflows.
- Spreadsheet Engines: Recalculating dependent formula cells without stale values.