Skip to content
Visual explainer 2h 30m to learn 4 steps

Topological sort

Order tasks in a DAG with Kahn's algorithm or DFS and detect impossible orderings.

By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.

Topic 34 of 54

In short

A topological order lists the vertices of a directed acyclic graph so every edge points forward. It answers questions like the order to take courses or build modules. Kahn's algorithm repeatedly removes vertices with no incoming edges; if some remain, the graph has a cycle.

Explained simply

Some jobs must happen before others. You must put on socks before shoes. A course needs its prerequisite first. A program module must be compiled after the modules it imports. A topological sort turns these rules into one ordered list where every "before" rule is respected.

We draw each job as a vertex and each rule "A before B" as an arrow from A to B. Then a topological order is a line-up of all vertices where every arrow points forward, from left to right.

This only works if the rules never loop. If A must come before B, B before C, and C before A, nothing can go first. A directed graph with no loops is called a DAG (directed acyclic graph). Every DAG has at least one topological order.

There are two standard algorithms, Kahn's algorithm and the DFS method. Both run in O(V + E), and both tell you when a loop makes the order impossible.

Press Play on a diagram to walk through it one step at a time.

FlowKahn's algorithm
  1. 1
    Count in-degrees

    For every vertex.

  2. 2
    Seed queue

    All vertices with in-degree 0.

  3. 3
    Pop and output

    Append u to the order.

  4. 4
    Decrement

    Each neighbour's in-degree; enqueue at 0.

  5. 5
    Check

    Fewer than V output means a cycle.

CompareKahn's algorithm versus DFS post-order
Kahn (BFS style)
  • Needs in-degree counts
  • No recursion, no depth limit
  • Cycle: output shorter than V
  • Easy to get layers and smallest order
DFS post-order
  • Needs three colours
  • Recursion or iterative stack
  • Cycle: edge to a grey vertex
  • Easy to report the cycle itself

In depth

Why every DAG can be ordered

Kahn's algorithm rests on one fact: every DAG has at least one vertex with in-degree 0, meaning no arrow points into it. Why? Pick any vertex and keep walking backwards along incoming arrows. If every vertex had an incoming arrow, you could walk forever. With only V vertices, you would eventually repeat one, and that repeat is a cycle. A DAG has no cycle, so the walk must stop at a vertex with nothing pointing in.

That vertex can safely go first. Remove it and its outgoing arrows. What remains is still a DAG, so it also has a vertex with in-degree 0. Repeat until nothing is left.

The same argument explains cycle detection. If the graph has a cycle, the vertices on it never reach in-degree 0, because each one keeps an arrow from the previous one. Kahn's algorithm then stops early with fewer than V vertices in the output.

Kahn's algorithm in practice

Count the in-degree of every vertex in one pass over the edges. Push every vertex with in-degree 0 into a queue. Then repeat: pop a vertex, add it to the output, and lower the in-degree of each of its neighbours by one. A neighbour that drops to 0 is now free and goes into the queue. Each vertex is pushed once and each edge is decreased once: O(V + E).

When several vertices are free at once, any choice is valid, which is why many topological orders can exist. If the problem wants the lexicographically smallest order, replace the queue with a min-heap (heapq). That costs O(V log V + E).

The vertices left with in-degree above 0 at the end are either on a cycle or wait on something that is. That list is useful in error messages, such as "cannot install: these packages depend on each other".

  • Queue gives any valid order in O(V + E)
  • heapq gives the smallest order in O(V log V + E)
  • Leftover in-degree above 0 means a cycle blocks those vertices

The DFS method: reverse post-order

Run a DFS and add each vertex to a list at the moment it finishes, after all its descendants are done. This is called post-order. Then reverse the list.

Why does that work? Take any edge u to v. If DFS reaches v from u, v finishes first, so v appears earlier in the post-order and later after reversing. If v was already finished, the same is true. The only bad case is when v is still grey, on the current path, but then u to v is a back edge, which means the graph has a cycle. So the three-colour rule from DFS doubles as the cycle check.

In Python, appending to a list and reversing once at the end is O(V). Avoid list.insert(0, x) inside the loop, which costs O(V) per call. For large graphs, use an iterative DFS to stay under the recursion limit.

SequenceDFS topological sort on A to B, B to C, A to C
Driver loop
DFS calls
Finished list
  1. 1visit(A) enters B, then C
    Driver loop to DFS calls: visit(A) enters B, then C
  2. 2C has no edges: append C
    DFS calls to Finished list: C has no edges: append C
  3. 3B is done: append B
    DFS calls to Finished list: B is done: append B
  4. 4A to C: C is already black, skip
    DFS calls to Finished list: A to C: C is already black, skip
  5. 5A is done: list is C, B, A
    DFS calls to Finished list: A is done: list is C, B, A
  6. 6Reverse: A, B, C
    Finished list to Driver loop: Reverse: A, B, C

Levels, parallel work and the critical path

If you run Kahn's algorithm one layer at a time, each layer is a group of jobs that can run in parallel, because none of them waits on another in the same layer. Build tools and CI systems use this idea to run independent steps together. The number of layers is the minimum number of rounds needed, for example the fewest semesters to finish all courses when there is no limit on courses per term.

A topological order also makes dynamic programming on DAGs easy. Process vertices in order, and when you reach v, all of its predecessors are already final. This gives the longest path in a DAG in O(V + E). With job durations as weights, that longest path is the critical path: the chain of jobs that decides the earliest possible finish time. Longest path is hard on general graphs, but easy on DAGs thanks to this order.

The order is unique exactly when the queue never holds more than one vertex at a time.

LayersKahn's layers for a small build
  1. 1
    Layer 0

    config and utils: no dependencies

  2. 2
    Layer 1

    db and auth: need utils or config

  3. 3
    Layer 2

    api: needs db and auth

  4. 4
    Layer 3

    app: needs api

Getting the edge direction right

Most wrong answers in topological sort problems come from arrows that point the wrong way. Decide the meaning once: an arrow from A to B means A must come before B. Then translate the input carefully.

In the classic course schedule problem, prerequisites[i] = [a, b] means you must take b before a. So the edge goes from b to a, and you increase the in-degree of a. If you build it the other way, you get the reverse order, which is still "valid" for the reversed graph, so tests with symmetric data may even pass.

Two more checks: include vertices that have no edges at all (they still need a place in the order), and decide what to return for a cycle. An empty list, None or an exception are all fine, as long as you never return a partial order that looks complete.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Define DAGs and dependency order~40m
  2. 2
    Implement Kahn's algorithm with in-degrees~40m
  3. 3
    Implement DFS post-order topological sort~40m
  4. 4
    Detect cycles in course schedules~40m

Key points

  • Time O(V + E), space O(V).
  • Only DAGs have a topological order.
  • Reverse DFS post-order is also a valid topological order.
  • There may be many valid orders.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
from collections import deque

def topo_order(n, edges):         # O(V + E)
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:
        adj[u].append(v); indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    order = []
    while q:
        u = q.popleft(); order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0: q.append(v)
    return order if len(order) == n else []   # [] means a cycle

Tracing Kahn's algorithm by hand, and hitting a cycle

Courses: math before physics, math before cs, cs before ai, physics before ai. Step 1: in-degrees are math 0, physics 1, cs 1, ai 2. Step 2: the queue starts with math. Pop math and output it; physics and cs drop to 0 and join the queue. Step 3: pop physics, then cs; ai drops 2 to 1 to 0. Step 4: pop ai. Output: math, physics, cs, ai. All 4 placed, so it is valid. Now add ai before math. math starts at in-degree 1, the queue starts empty, nothing is output, and 0 is less than 4: a cycle.

DFS topological sort with a clear cycle error

Here graph[u] lists the jobs that must come after u. Step 1: visit each unvisited job. Step 2: mark it grey, visit its successors, then mark it black and append it. Step 3: if a successor is grey, raise an error that names the edge, which is much more helpful than an empty list. For the example, the finished list is app, api, db, utils, and reversing gives utils, db, api, app.

python
def topo_dfs(graph):              # graph[u] = jobs that must come after u
    state, order = {}, []          # missing = white, 1 = grey, 2 = black
    def visit(u):
        state[u] = 1
        for v in graph.get(u, []):
            if state.get(v) == 1:
                raise ValueError(f"cycle through {u} -> {v}")
            if v not in state:
                visit(v)
        state[u] = 2
        order.append(u)
    for u in graph:
        if u not in state:
            visit(u)
    return order[::-1]

print(topo_dfs({"app": [], "utils": ["db", "api"], "db": ["api"], "api": ["app"]}))

Quick reference

  • Topological order exists if and only if the directed graph has no cycle
  • Kahn: queue the in-degree 0 vertices, pop, decrement neighbours, repeat
  • Kahn output shorter than V means there is a cycle
  • DFS method: append on finish, reverse at the end
  • Lexicographically smallest order: use heapq, O(V log V + E)
  • Course schedule [a, b] means b before a: edge b -> a
  • Longest path in a DAG: DP in topological order, O(V + E)

Common mistakes

  • Forgetting to detect cycles and returning a partial order.
  • Reversing edge direction when modelling prerequisites.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Kahn's algorithm outputs 7 vertices for a graph with 9 vertices. What does that tell you?

Question 2

2In the DFS method, when is a vertex added to the list that you later reverse?

Question 3

3prerequisites = [[1, 0]] in the course schedule problem means you take course 0 before course 1. Which edge do you add?

Question 4

4When is the topological order of a DAG unique?

Question 5

5What is the time complexity of Kahn's algorithm with a plain queue?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Edges: a -> c, b -> c, c -> d. List every valid topological order by hand.

  2. Exercise 2medium

    Return the minimum number of semesters to finish all n courses, if you can take any number of courses per semester once their prerequisites are done. Return -1 if impossible.

  3. Exercise 3hard

    Return the lexicographically smallest topological order of vertices 0..n-1, or [] if there is a cycle.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can a graph with a cycle be topologically sorted?
No. In a cycle every vertex must come before another vertex of the same cycle, which is impossible. Both Kahn's algorithm and the DFS method detect this.
Should I use Kahn's algorithm or DFS for topological sort?
Kahn's algorithm is easier to get right, has no recursion limit and gives layers naturally. DFS is handy when you already have a DFS or want to report the exact cycle.
Where is topological sort used in real software?
Build systems like make and Bazel, package managers resolving dependencies, task schedulers such as Airflow, and spreadsheets recalculating cells all order work this way.

Go deeper

ShareXLinkedInWhatsApp