Skip to content

Chapter 21. Topological Ordering

A topological ordering is a linear arrangement of the vertices of a directed graph that respects every arc direction. It turns a partial order given by a directed acyclic graph into a single list.

Topological ordering is defined only for directed graphs. It is especially important for directed acyclic graphs, because a directed graph has a topological ordering exactly when it has no directed cycle. This equivalence is one of the basic structural facts about DAGs.

21.1 Definition

Let

D=(V,A) D = (V,A)

be a directed graph. A topological ordering of DD is an ordering of its vertices

v1,v2,,vn v_1, v_2, \ldots, v_n

such that for every arc

(vi,vj)A, (v_i,v_j) \in A,

the vertex viv_i appears before the vertex vjv_j in the list.

Equivalently, every arc points from left to right when the vertices are written in topological order.

If an arc is written as

uv, u \to v,

then uu must appear earlier than vv.

The ordering does not require every pair of vertices to be related by an arc or path. It only requires the listed order to respect the constraints that are present.

21.2 First Example

Consider the directed graph with arcs

ab,ac,bd,cd. a \to b, \qquad a \to c, \qquad b \to d, \qquad c \to d.

The ordering

a,b,c,d a,b,c,d

is topological. Each arc points forward:

ab,ac,bd,cd. a \to b, \qquad a \to c, \qquad b \to d, \qquad c \to d.

The ordering

a,c,b,d a,c,b,d

is also topological.

There is no arc from bb to cc, and no arc from cc to bb. Therefore either bb or cc may come first, provided both remain after aa and before dd.

The ordering

b,a,c,d b,a,c,d

is not topological, because the arc

ab a \to b

requires aa to appear before bb.

21.3 Topological Ordering and DAGs

A directed graph has a topological ordering if and only if it is a DAG.

We prove both directions.

First, suppose a directed graph has a topological ordering. If it contained a directed cycle

v0v1vk1v0, v_0 \to v_1 \to \cdots \to v_{k-1} \to v_0,

then the ordering would require

v0<v1<<vk1<v0. v_0 < v_1 < \cdots < v_{k-1} < v_0.

This is impossible. Hence a graph with a topological ordering has no directed cycle.

Conversely, suppose the graph is a finite DAG. Every finite nonempty DAG has at least one source, a vertex with in-degree zero. Place such a source first. Remove it and all outgoing arcs. The remaining graph is still a DAG. Repeat the argument. This process eventually lists every vertex and produces a topological ordering.

Thus acyclicity is exactly the condition needed for topological ordering.

21.4 Sources and Construction

A source is a vertex with no incoming arcs.

In a topological ordering, a source is a natural candidate for the first position. Since no arc enters it, no other vertex is required to appear before it.

More generally, after some vertices have already been placed in the ordering, we look at the remaining graph. Any source in the remaining graph may be placed next.

This gives the basic constructive principle:

Repeatedly remove a source. \text{Repeatedly remove a source.}

The removed vertices, in the order of removal, form a topological ordering.

This is the idea behind Kahn’s algorithm, a standard linear-time topological sorting algorithm.

21.5 Kahn’s Algorithm

Kahn’s algorithm builds a topological ordering by repeatedly selecting vertices of in-degree zero.

Given a finite directed graph D=(V,A)D=(V,A):

  1. Compute the in-degree of every vertex.
  2. Put all vertices of in-degree zero into a set or queue SS.
  3. Remove a vertex uu from SS.
  4. Append uu to the output list.
  5. For each arc uvu \to v, remove that arc and decrease the in-degree of vv.
  6. If vv now has in-degree zero, insert vv into SS.
  7. Continue until SS is empty.

If every vertex has been output, the list is a topological ordering.

If some vertices remain, then the remaining graph has no source. In a finite directed graph, this means a directed cycle remains. Therefore the original graph was not a DAG.

21.6 Example of Kahn’s Algorithm

Let

V={a,b,c,d,e} V = \{a,b,c,d,e\}

and

A={(a,b),(a,c),(b,d),(c,d),(d,e)}. A = \{(a,b),(a,c),(b,d),(c,d),(d,e)\}.

The in-degrees are:

VertexIn-degree
aa0
bb1
cc1
dd2
ee1

The only source is aa. Place aa first.

After removing aa, the vertices bb and cc both have in-degree zero. We may choose either.

Choose bb. Then choose cc. After both are removed, dd has in-degree zero. Then after removing dd, ee has in-degree zero.

One possible topological ordering is

a,b,c,d,e. a,b,c,d,e.

Another is

a,c,b,d,e. a,c,b,d,e.

The algorithm may produce different valid orderings depending on how it chooses among available sources.

21.7 Depth-First Search Method

Topological ordering can also be computed by depth-first search.

Run DFS on the directed graph. When a vertex has finished exploring all of its outgoing neighbors, place it at the front of a list. Equivalently, record vertices in reverse finishing order.

If the graph is a DAG, this reverse finishing order is a topological ordering. This method is another standard linear-time construction.

The reason is as follows. If there is an arc

uv, u \to v,

then DFS finishes vv before uu, unless vv was already fully processed. In either case, reversing finishing order places uu before vv.

DFS also detects directed cycles. If DFS reaches a vertex that is currently active on the recursion stack, then the graph contains a directed cycle and no topological ordering exists.

21.8 Non-Uniqueness

Topological orderings are usually not unique.

Whenever two vertices are unrelated by reachability, either may appear before the other, provided all other constraints are respected.

For example, in the graph

ab,ac, a \to b, \qquad a \to c,

both

a,b,c a,b,c

and

a,c,b a,c,b

are topological orderings.

A DAG has a unique topological ordering only under stronger conditions. One useful characterization is that the ordering is unique exactly when each consecutive pair in the ordering is forced by an arc, or equivalently when the DAG contains a directed Hamiltonian path consistent with the ordering.

21.9 Topological Ordering as Linear Extension

A DAG defines a partial order by reachability.

Define

uv u \preceq v

if u=vu=v or there is a directed path from uu to vv.

A topological ordering is a linear extension of this partial order. It places all vertices in one sequence while preserving the required precedence constraints.

This interpretation is important. The DAG may not compare every pair of vertices, but a topological ordering must still choose some order for incomparable pairs.

Thus topological sorting converts partial order into total order without violating the partial order.

21.10 Applications to Scheduling

Topological ordering is the basic model for dependency scheduling.

Suppose vertices represent tasks, and an arc

uv u \to v

means that task uu must be completed before task vv begins.

Then a topological ordering gives a valid schedule. Every task appears after all of its prerequisites.

Examples include:

SystemVerticesArcs
Course planningCoursesprerequisite before course
Build systemsTargetsdependency before dependent
Project planningTasksrequired task before later task
CompilersComputationsvalue before use
SpreadsheetsCellsreferenced cell before formula cell
Package managersPackagesdependency before dependent

Topological ordering is widely used for dependency-driven execution and scheduling.

21.11 Cycle Detection Through Topological Sorting

Topological sorting also detects cycles.

During Kahn’s algorithm, if vertices remain but no source exists, then the remaining subgraph contains a directed cycle. Therefore no topological ordering exists.

This gives a practical test:

ResultMeaning
All vertices are outputThe graph is a DAG
Some vertices remainThe graph contains a directed cycle

This is useful in systems where cycles represent invalid dependency structure, such as build rules, imports, package dependencies, and task graphs.

21.12 Complexity

Topological sorting can be performed in linear time:

O(V+A). O(|V| + |A|).

The algorithm visits each vertex and processes each arc a constant number of times.

Kahn’s algorithm achieves this bound by maintaining in-degree counts and adjacency lists. DFS topological sorting also achieves this bound by running one depth-first traversal over the graph.

This linear complexity makes topological sorting practical even for large graphs.

21.13 Topological Ordering in Weighted DAGs

Topological order is useful beyond scheduling. It also supports efficient dynamic programming on DAGs.

For example, shortest paths in a weighted DAG can be computed by processing vertices in topological order. When a vertex is processed, all possible incoming contributions from earlier vertices have already been considered. This avoids repeated relaxation cycles and gives a linear-time algorithm in the number of vertices and arcs.

The same principle applies to longest paths in DAGs, counting paths, evaluating expression graphs, and many dynamic programming recurrences.

Acyclicity turns recurrence into ordered computation.

21.14 Common Mistakes

A common mistake is to attempt topological sorting on an undirected graph. Topological ordering is a concept for directed graphs.

Another mistake is to think that every directed graph has a topological ordering. Directed cycles make topological ordering impossible.

A third mistake is to expect the ordering to be unique. Many DAGs have several valid topological orderings.

A fourth mistake is to reverse the meaning of dependency arcs. If uvu \to v means “uu must come before vv,” then uu appears before vv. If the convention is reversed, the interpretation of the order is reversed as well.

21.15 Summary

A topological ordering of a directed graph is a linear ordering of vertices in which every arc points from an earlier vertex to a later vertex.

A finite directed graph has a topological ordering exactly when it is a DAG. This makes topological sorting both a construction method and a cycle-detection method.

Two standard algorithms compute topological orderings in linear time: Kahn’s algorithm, which repeatedly removes sources, and the depth-first search method, which uses reverse finishing order.

Topological ordering is the main bridge between directed acyclic graphs and ordered computation. It is used in scheduling, dependency resolution, compilation, dynamic programming, project planning, and many other systems where one object must precede another.