Topological sorting

Also known as: topological sort

On this page 7

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.

ConceptMeaningRole in the sort
Directed acyclic graphDirected edges, no cyclesThe only input type with a valid order
In-degreeNumber of incoming edgesZero means the vertex is ready
Source vertexVertex with in-degree zeroCandidate for the next output position
Sink vertexVertex with no outgoing edgesFinishes first in the DFS method
Partial orderConstraints on some pairs onlyAllows several valid results
Core concepts behind topological sorting

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.

PropertyKahn’s algorithmDFS post-order
Time complexityO(V + E)O(V + E)
Extra spaceIn-degree array plus queueVisited states plus call stack
Cycle detectionOutput shorter than VBack edge to in-progress vertex
Iteration styleNaturally iterativeRecursive unless rewritten
Deep graph riskNoneStack overflow on long chains
Parallel levelsEasy to extract by wavesRequires extra bookkeeping
Comparison of the two standard methods

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.

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.

ProblemWhat the order enablesTypical complexity
Longest path in a DAGRelax edges in order; critical pathO(V + E)
Shortest path in a DAGHandles negative weights without Bellman–FordO(V + E)
Counting pathsSum path counts from predecessorsO(V + E)
Level schedulingGroup vertices into parallel wavesO(V + E)
Strongly connected componentsCondensation graph is a DAGO(V + E)
Problems that rely on a topological order

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.

ApplicationVerticesEdge from A to B means
Build systemsSource files and targetsA must be built before B
Package managersPackages and versionsB depends on A
Spreadsheet recalculationCellsB references the value of A
Course planningCoursesA is a prerequisite of B
Data pipelinesTasks in a workflowB consumes the output of A
Compiler passesDeclarations or modulesB uses a symbol defined in A
Typical applications and their graph models

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.