Topological sorting is the process of arranging the vertices of a directed acyclic graph (DAG) in a linear order such that for every directed edge from u to v, u appears before v. In the study of algorithms within programming, a topological sort turns a web of dependency relations into a sequence that can be executed, compiled or scheduled one step at a time.
A topological order exists if and only if the graph has no directed cycle. Most graphs admit many valid orders, so a topological sort produces one acceptable answer rather than a unique one. The two classic methods, Kahn’s algorithm and a depth-first search variant, both run in O(V + E) time, which is linear in the size of the graph.
How a topological sort resolves dependencies
A topological sort works by repeatedly emitting a vertex whose prerequisites are already satisfied. A vertex with in-degree zero has no incoming edges, so nothing must precede it; once it is placed in the output, its outgoing edges are conceptually removed and its successors move closer to being ready.
The order is a linear extension of a partial order. The graph states only which pairs must be ordered; any two vertices without a directed path between them are mutually unordered, and the algorithm may place them in either sequence. This freedom is why build tools, package managers and spreadsheet engines can produce different but equally correct execution plans.
The following table summarizes the core concepts that every implementation relies on.
| Concept | Meaning | Role in the sort |
|---|---|---|
| Directed acyclic graph | Directed edges, no cycles | The only input type with a valid order |
| In-degree | Number of incoming edges | Zero means the vertex is ready |
| Source vertex | Vertex with in-degree zero | Candidate for the next output position |
| Sink vertex | Vertex with no outgoing edges | Finishes first in the DFS method |
| Partial order | Constraints on some pairs only | Allows several valid results |
Kahn’s algorithm and the depth-first search method
Kahn’s algorithm is the queue-based approach. It first computes the in-degree of every vertex, places all zero in-degree vertices in a queue, and then repeatedly removes a vertex, appends it to the output and decrements the in-degree of each successor. Any successor whose count falls to zero joins the queue.
The DFS-based method explores the graph recursively and records each vertex when its exploration finishes, that is, after all descendants have been visited. Reversing this post-order yields a topological order. Cycle detection uses three vertex states: unvisited, in progress and done; meeting an in-progress vertex reveals a back edge, which proves a cycle.
Both methods are correct and linear, but they differ in behavior that matters in practice, as the comparison below shows.
| Property | Kahn’s algorithm | DFS post-order |
|---|---|---|
| Time complexity | O(V + E) | O(V + E) |
| Extra space | In-degree array plus queue | Visited states plus call stack |
| Cycle detection | Output shorter than V | Back edge to in-progress vertex |
| Iteration style | Naturally iterative | Recursive unless rewritten |
| Deep graph risk | None | Stack overflow on long chains |
| Parallel levels | Easy to extract by waves | Requires extra bookkeeping |
Replacing the plain queue in Kahn’s algorithm with a priority queue produces the lexicographically smallest order, at a cost of O(V log V + E). This variant is useful when results must be deterministic and reproducible across runs.
Variants and related graph problems
Several problems build directly on a topological order. Processing vertices in that order lets dynamic programming compute values over a DAG in a single pass, because every predecessor is finished before its dependents are evaluated.
| Problem | What the order enables | Typical complexity |
|---|---|---|
| Longest path in a DAG | Relax edges in order; critical path | O(V + E) |
| Shortest path in a DAG | Handles negative weights without Bellman–Ford | O(V + E) |
| Counting paths | Sum path counts from predecessors | O(V + E) |
| Level scheduling | Group vertices into parallel waves | O(V + E) |
| Strongly connected components | Condensation graph is a DAG | O(V + E) |
Topological sorting differs from comparison-based sorting algorithms such as quicksort or merge sort. Those algorithms impose a total order on keys, whereas a topological sort respects only the explicit edges of a graph. It is also distinct from plain breadth-first search: Kahn’s algorithm resembles BFS in using a queue, but it advances by in-degree readiness, not by distance from a start vertex.
Where topological sorting is used in software
Topological sorting appears wherever software must respect prerequisites. Build systems order compilation targets, package managers order installations, database migration tools apply schema changes in sequence, and workflow engines schedule pipeline stages.
The table below maps common applications to what the vertices and edges represent.
| Application | Vertices | Edge from A to B means |
|---|---|---|
| Build systems | Source files and targets | A must be built before B |
| Package managers | Packages and versions | B depends on A |
| Spreadsheet recalculation | Cells | B references the value of A |
| Course planning | Courses | A is a prerequisite of B |
| Data pipelines | Tasks in a workflow | B consumes the output of A |
| Compiler passes | Declarations or modules | B uses a symbol defined in A |
Many standard libraries ship a ready implementation, for example graphlib.TopologicalSorter in Python, which also supports incremental readiness for parallel workers. Using a tested library is usually safer than a hand-written version.
Limitations and common mistakes
The most frequent error is reversing the edge direction. If an edge means “depends on” rather than “must precede”, the resulting order is backward. Teams should define the edge semantics explicitly before writing any code.
- Ignoring cycles: an implementation that does not verify that all V vertices were emitted can silently return a partial, misleading order.
- Assuming uniqueness: tests that compare against one fixed order fail when a different valid order appears; tests should verify the edge constraints instead.
- Recursion depth: the DFS method can exceed the call stack on dependency chains of tens of thousands of vertices.
- Dynamic graphs: recomputing the full order after every edge insertion is wasteful; incremental topological ordering algorithms exist for frequently changing graphs.
- Reporting cycles poorly: users need the actual cycle path, not only a failure flag, to fix circular dependencies.
In simple terms
Topological sorting is a way to put tasks in an order that never breaks a dependency. Think of getting dressed: socks must go on before shoes, and a shirt before a jacket, but it does not matter whether the shirt or the socks come first.
The method keeps picking any task that has nothing left waiting before it, writes it down and moves on. If some tasks wait on each other in a circle, no valid order exists, and the method reports that circular dependency instead of guessing.
A practical example
A platform team maintains a monorepo with about 400 internal libraries. Before each release, the build tool reads every library’s declared dependencies, builds a graph with roughly 1,900 edges and runs Kahn’s algorithm. Libraries with no dependencies form the first wave, and each later wave contains libraries whose prerequisites are complete.
Because the waves expose independent work, the team runs up to 16 builds in parallel. One morning the sort emits only 397 libraries, and the tool prints the cycle it found: an authentication library and a logging library had started importing each other. A developer extracts the shared code into a third library, the cycle disappears, and the full build completes in 11 minutes instead of failing late in the pipeline.