TExcelTAD
Home › Data Structures & Algorithms › Topological Sort

Topological Sort

Some tasks must happen before others: you install the foundation before the walls, compile a library before the program that uses it, take Programming 1 before Programming 2. Draw each task as a vertex and each "must come before" rule as a directed edge, and you get a directed acyclic graph (DAG). A topological order lists the vertices so that every edge points forward: each task comes after all of its prerequisites.

A topological order exists exactly when the graph has no cycle (you can't schedule "A before B before A"). A DAG usually has several valid orders.

Our example: a study plan

Course Requires
Intro (I) —
Math (M) —
Programming (P) Intro
Data Structures (D) Programming, Math
Web (W) Programming
Algorithms (A) Data Structures
Capstone (C) Algorithms, Web

Kahn's algorithm

Kahn's algorithm (1962) repeatedly takes a vertex with no remaining incoming edges ("all prerequisites done"):

  1. Count the incoming edges (in-degree) of every vertex. Vertices with in-degree 0 are ready.
  2. Take a ready vertex, append it to the order, and remove its outgoing edges: each neighbour's in-degree drops by one, and any neighbour that reaches 0 becomes ready.
  3. Repeat until no vertex is ready. If some vertices were never output, the graph has a cycle.

When several vertices are ready, this animation (and our code) takes them in alphabetical order:

python · try it yourself
def kahn(nodes, edges):
    indegree = {v: 0 for v in nodes}
    out = {v: [] for v in nodes}
    for u, v in edges:
        out[u].append(v)
        indegree[v] += 1
    ready = sorted(v for v in nodes if indegree[v] == 0)
    print("ready at start:", ready)
    order = []
    while ready:
        u = ready.pop(0)                 # alphabetically first ready vertex
        order.append(u)
        for v in sorted(out[u]):
            indegree[v] -= 1
            if indegree[v] == 0:
                ready.append(v)
        ready.sort()
        print(f"output {u}, ready now {ready}")
    if len(order) != len(nodes):
        raise ValueError("cycle: no topological order exists")
    return order

nodes = ["I", "M", "P", "D", "W", "A", "C"]
edges = [("I", "P"), ("P", "D"), ("M", "D"), ("P", "W"), ("D", "A"), ("A", "C"), ("W", "C")]
print("order:", " -> ".join(kahn(nodes, edges)))
ready at start: ['I', 'M']
output I, ready now ['M', 'P']
output M, ready now ['P']
output P, ready now ['D', 'W']
output D, ready now ['A', 'W']
output A, ready now ['W']
output W, ready now ['C']
output C, ready now []
order: I -> M -> P -> D -> A -> W -> C

The order matches the animation's final frame. Each vertex and each edge is handled once, so Kahn's algorithm runs in O(V + E) (plus the sorting we added for a deterministic order).

DFS-based topological sort

A depth-first search gives another algorithm: when a vertex finishes (all its descendants are explored), every vertex it points to has already finished. So the reverse of the finishing order is a topological order.

python · try it yourself
graph = {"I": ["P"], "M": ["D"], "P": ["D", "W"], "D": ["A"], "W": ["C"], "A": ["C"], "C": []}

def topo_dfs(graph):
    visited, finished = set(), []

    def dfs(u):
        visited.add(u)
        for v in graph[u]:
            if v not in visited:
                dfs(v)
        finished.append(u)          # u is done after all its successors

    for u in sorted(graph):
        if u not in visited:
            dfs(u)
    print("finishing order:", finished)
    return finished[::-1]

print("topological order:", " -> ".join(topo_dfs(graph)))
finishing order: ['C', 'A', 'D', 'W', 'P', 'I', 'M']
topological order: M -> I -> P -> W -> D -> A -> C

A different order than Kahn's, but just as valid: check that every edge points forward.

python · try it yourself
def is_topological(order, edges):
    position = {v: i for i, v in enumerate(order)}
    return all(position[u] < position[v] for u, v in edges)

edges = [("I", "P"), ("P", "D"), ("M", "D"), ("P", "W"), ("D", "A"), ("A", "C"), ("W", "C")]
print(is_topological(["I", "M", "P", "D", "A", "W", "C"], edges))
print(is_topological(["M", "I", "P", "W", "D", "A", "C"], edges))
print(is_topological(["I", "P", "W", "C", "M", "D", "A"], edges))   # C before A: invalid
True
True
False

Scheduling in parallel: levels

If several tasks can run at the same time, group them into levels: everything that is ready together forms one level. The number of levels is the minimum number of "semesters" (or build rounds) needed:

python · try it yourself
nodes = ["I", "M", "P", "D", "W", "A", "C"]
edges = [("I", "P"), ("P", "D"), ("M", "D"), ("P", "W"), ("D", "A"), ("A", "C"), ("W", "C")]
indegree = {v: 0 for v in nodes}
for _, v in edges:
    indegree[v] += 1

level = sorted(v for v in nodes if indegree[v] == 0)
semester = 1
while level:
    print(f"semester {semester}: {level}")
    nxt = []
    for u in level:
        for a, b in edges:
            if a == u:
                indegree[b] -= 1
                if indegree[b] == 0:
                    nxt.append(b)
    level, semester = sorted(nxt), semester + 1
semester 1: ['I', 'M']
semester 2: ['P']
semester 3: ['D', 'W']
semester 4: ['A']
semester 5: ['C']

Where topological sorting is used

  • Build systems (Make, Gradle, bundlers): compile dependencies first.
  • Package managers: install packages after their dependencies.
  • Spreadsheets: recalculate cells after the cells they refer to.
  • Task schedulers and CI pipelines: run jobs in dependency order, in parallel by level.
  • Shortest paths in DAGs: relax edges in topological order for an O(V + E) algorithm, even with negative weights.

Test yourself

When does a directed graph have a topological order?

  1. Always
  2. Exactly when it has no cycles
  3. Only when it is a tree
  4. Only when it is connected

In Kahn's algorithm, which vertices are ready to be output?

  1. Those with no outgoing edges
  2. Those with in-degree 0 (no remaining prerequisites)
  3. The vertex with the most edges
  4. Any vertex

In the DFS-based method, how is the topological order obtained?

  1. The order vertices are first visited
  2. The reverse of the order in which vertices finish
  3. Alphabetical order
  4. BFS order