AlgoViz

Topological sort

medium 20 min

A topological sort lists the nodes of a directed graph so that every edge u → v has u before v: a valid order for tasks with prerequisites.

Chapter mnemonic

Kahn’s topological sort

Bake what is ready. Cross it off. Unlock the next recipe.

The ready queue is empty, and three recipes remain. What does that tell you?

The remaining dependencies contain a cycle. A full topological ordering is impossible.

Video lesson · Chapter 1 of 8

The bindery schedule

0:00 / 5:28

Topological sort in 75 seconds

1:19Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Draw the dependencies. Each rule "u must come before v" is a directed edge u → v; the graph must have no cycle

Understand it

Start here

What topological sort is

You have tasks, and some must happen before others: CS101 before CS201, compile utils before main, underwear before pants. Draw each rule as a directed edge u→vu \to v and a topological sort is a list of all the nodes in which every edge points forward, from earlier to later. It does not sort by value; it sorts by dependency.

  • Recap: directed graphs

    Vertices, one-way edges, in-degree and out-degree, adjacency lists. All covered in Intro to graphs; this page builds on it.

  • DAG

    A Directed Acyclic Graph: one-way edges and no way to follow arrows back to where you started.

  • Linear order

    Every node exactly once, and for each edge u→vu \to v, uu appears before vv.

  • Usually many answers

    Five courses below have 5 valid orders out of 5!=1205! = 120 arrangements. Any one of them is correct.

The course schedule used throughout this page

An arrow means "take before". CS201 needs CS101 and Math; CS301 needs CS102 and CS201.

The precondition

Only DAGs have an order

If the arrows form a loop, there is no first node in it. Each course on the loop waits on the one before it, all the way round, so none of them can ever start. A topological order exists if and only if the directed graph has no cycle.

A cycle: who goes first?

Prog can go first, but DS, Algo and OS each wait on another member of the loop. No order satisfies all four arrows.

Existence

G has a topological order  ⟺  G is a DAGG \text{ has a topological order} \iff G \text{ is a DAG}
(⇒\Rightarrow) On a cycle v1→v2→⋯→vk→v1v_1 \to v_2 \to \dots \to v_k \to v_1 an order would need v1v_1 before v2v_2 before …\dots before v1v_1, which is impossible. (⇐\Leftarrow) Kahn's algorithm below builds an order for every DAG.

Method 1

Kahn's algorithm: peel off the zeros

A node's in-degree is how many arrows point into it: how many prerequisites it still waits on. A node with in-degree 00 is ready right now. Output one, delete its outgoing edges (decrement each successor's in-degree), and new zeros appear. Keep the ready nodes in a queue and repeat until it is empty. Remember it as ZERO.

ZERO
  1. 1Zerofind every in-degree 0 node
  2. 2Enqueuethey are ready
  3. 3Removepop one, decrement successors
  4. 4Outputappend to the order
Repeat: back to Zero

Loop until the queue is empty, then compare the output count with V.

Kahn's algorithm

Each node enters the queue exactly once, at the moment its count reaches zero.
Python
from collections import dequedef kahn(n, adj):    indeg = [0] * n    for u in range(n):        for v in adj[u]:            indeg[v] += 1    queue = deque(u for u in range(n) if indeg[u] == 0)    order = []    while queue:        u = queue.popleft()        order.append(u)        for v in adj[u]:            indeg[v] -= 1            if indeg[v] == 0:                queue.append(v)    return order if len(order) == n else []   # [] means a cycleadj = [[1, 3], [4], [3], [4], []]print(kahn(5, adj))                            # [0, 2, 1, 3, 4]print(kahn(3, [[1], [2], [0]]))                # [] (0 -> 1 -> 2 -> 0)
Nodes are 0 to n - 1 and adj[u] lists the nodes that must come after u. The course graph is CS101=0, CS102=1, Math=2, CS201=3, CS301=4.
Edit and run it in your browser

Worked example

Kahn on the course schedule

PopIn-degree changesQueue afterOrder so far
startCS101 0, CS102 1, Math 0, CS201 2, CS301 2CS101, Mathempty
CS101CS102 1 → 0, CS201 2 → 1Math, CS102CS101
MathCS201 1 → 0CS102, CS201CS101, Math
CS102CS301 2 → 1CS201CS101, Math, CS102
CS201CS301 1 → 0CS301CS101, Math, CS102, CS201
CS301noneemptyCS101, Math, CS102, CS201, CS301
Five pops, five edge decrements. A bold 0 is the moment a course becomes ready and joins the queue.

The in-degrees add up to the edge count

∑v∈Vindeg⁡(v)=∣E∣0+1+0+2+2=5\sum_{v \in V} \operatorname{indeg}(v) = |E| \qquad 0 + 1 + 0 + 2 + 2 = 5
Every edge has exactly one head, so it adds 1 to exactly one in-degree. Kahn subtracts each of those 1s once, which is why it does ∣E∣|E| decrements in total.

Method 2

DFS: reverse the finish order

Run a depth-first search from every unvisited node and append a node to a list post only when it finishes, after all its successors are done. Whatever comes after a node finishes before it, so post lists the nodes back to front. Reverse it and you have a topological order.

DFS topological sort with three colours

GRAY means on the current path, BLACK means finished. Only GRAY neighbours signal a cycle.
Python
def dfs_topo(n, adj):    WHITE, GRAY, BLACK = 0, 1, 2    color = [WHITE] * n    post = []    def dfs(u):        color[u] = GRAY        for v in adj[u]:            if color[v] == GRAY:                raise ValueError("cycle")            if color[v] == WHITE:                dfs(v)        color[u] = BLACK        post.append(u)          # u finishes after all its successors    for u in range(n):        if color[u] == WHITE:            dfs(u)    return post[::-1]adj = [[1, 3], [4], [3], [4], []]print(dfs_topo(5, adj))         # [2, 0, 3, 1, 4]
The same course graph. Recursion is fine here; for very long chains use an explicit stack, see Iterative DFS.
Edit and run it in your browser

Worked example

DFS on the same courses

EventPath (GRAY)post (finish order)
enter CS101, CS102, CS301CS101, CS102, CS301empty
CS301 has no edges: finishCS101, CS102CS301
CS102 done: finishCS101CS301, CS102
enter CS201; CS301 is BLACK, skipCS101, CS201CS301, CS102
CS201, then CS101 finishemptyCS301, CS102, CS201, CS101
enter Math; CS201 is BLACK; finishemptyCS301, CS102, CS201, CS101, Math
Reversed: Math, CS101, CS201, CS102, CS301.

Kahn gave CS101, Math, CS102, CS201, CS301 and DFS gave Math, CS101, CS201, CS102, CS301. Both are correct. The full list of valid orders for this graph is: CS101, CS102, Math, CS201, CS301; CS101, Math, CS102, CS201, CS301; CS101, Math, CS201, CS102, CS301; Math, CS101, CS102, CS201, CS301; and Math, CS101, CS201, CS102, CS301. CS301 is always last because it is the only node everything leads to.

Cycles

Cycle detection with three colours

In a directed graph, "already visited" is not enough to call a cycle. A node finished on a different branch (BLACK) is harmless; only a node still on the current path (GRAY) closes a loop. So DFS keeps three states: WHITE not started, GRAY in progress, BLACK done. Kahn needs no colours at all: if the queue empties before all VV nodes are output, the leftovers sit on or behind a cycle.

A node's colour over time

Each node changes colour exactly twice, which is part of why DFS is O(V + E).
Edge u → vColour of v when seenMeaning for topological sort
Tree edgeWHITERecurse into v
Back edgeGRAYCycle: v is an ancestor of u on the current path
Forward edgeBLACK (a descendant of u)Harmless: v already finished
Cross edgeBLACK (another branch)Harmless: like CS201 → CS301 above
A directed graph is acyclic exactly when DFS finds no back edge.

Proofs

Why both methods are correct

DFS: finish times run against the edges

For every edge u→v in a DAG:f(v)<f(u)\text{For every edge } u \to v \text{ in a DAG:} \quad f(v) < f(u)
f(x)f(x) is the moment xx turns BLACK. Sorting by decreasing ff (reversing post) therefore puts uu before vv for every edge.

Proof. Look at the moment DFS examines edge u→vu \to v; uu is GRAY. If vv is WHITE, DFS enters vv and finishes it before returning to uu, so f(v)<f(u)f(v) < f(u). If vv is BLACK, it already finished, so again f(v)<f(u)f(v) < f(u). If vv were GRAY, vv would be an ancestor of uu and v→⋯→u→vv \to \dots \to u \to v would be a cycle, which a DAG does not have. Every case gives f(v)<f(u)f(v) < f(u).

Kahn: every DAG has a source

G a non-empty DAG  ⟹  ∃ v:indeg⁡(v)=0G \text{ a non-empty DAG} \implies \exists\, v : \operatorname{indeg}(v) = 0
Walk backwards along incoming edges from any node. Within VV steps you either stop at a node with no incoming edge or revisit a node, and a revisit is a cycle.

Proof of Kahn. Outputting a source and deleting its edges leaves a smaller graph that is still a DAG, so it has a source too; by induction Kahn outputs all VV nodes, and each node is output only after all its predecessors were output. Conversely, if Kahn stops early, every leftover node has in-degree at least 1 from other leftovers, so walking backwards among them must repeat a node: a cycle. That is exactly why the count check is a correct cycle test.

Complexity

Cost: O(V + E), and which method to use

Kahn's running time

T=O(V)⏟init indeg+O(E)⏟count edges+O(V)⏟each node queued once+O(E)⏟each edge decremented once=O(V+E)T = \underbrace{O(V)}_{\text{init indeg}} + \underbrace{O(E)}_{\text{count edges}} + \underbrace{O(V)}_{\text{each node queued once}} + \underbrace{O(E)}_{\text{each edge decremented once}} = O(V + E)
DFS is the same: each node is entered once and each adjacency list scanned once. Extra space is O(V)O(V) for in-degrees or colours, the queue or recursion, and the output. Rescanning all nodes for a zero after every pop instead would cost O(V2+E)O(V^2 + E).
AspectKahn's (BFS style)DFS post-order
Core dataIn-degree array + queueColour array + recursion stack
Cycle detectionOutput count != VEdge to a GRAY node (back edge)
Result orderDirectReversed finish order
StyleIterativeRecursive (or explicit stack)
Easy extrasLevels / min rounds, smallest order with a heapFinding the actual cycle, reachability
Watch out forUsing list.pop(0) as the queuePython's recursion limit (about 1,000)

Reach for Kahn when

  • You need rounds, levels or the minimum number of semesters.
  • You want a specific order, such as the lexicographically smallest.
  • The graph may be deep: no recursion limit to worry about.

Reach for DFS when

  • You need to report the cycle itself, not just that one exists.
  • You are already running DFS for something else, such as reachability.
  • Arrows mean "depends on" and post-order gives the answer directly.

Beyond the basics

Levels, smallest order, unique order, longest path

  • Levels (parallel rounds)

    Process Kahn's queue one level at a time. The number of levels is the fewest rounds, which equals the number of nodes on the longest chain.

  • Smallest order

    Swap the queue for a min-heap: always output the smallest ready node. O(Vlog⁡V+E)O(V \log V + E).

  • Is the order unique?

    Exactly when the queue never holds two nodes at once. Then consecutive nodes are joined by edges: a Hamiltonian path.

  • DP on a DAG

    Process nodes in topological order and every predecessor is final before you need it: longest path, shortest path with negative weights, path counting.

The task pipeline in rounds

Clean and Parse run side by side. Four rounds, because Load, Clean, Process, Export is a chain of four.

Longest path in a DAG in one pass

dist[v]=max⁡u→v(dist[u]+w(u,v)),nodes taken in topological order\text{dist}[v] = \max_{u \to v} \big(\text{dist}[u] + w(u, v)\big), \quad \text{nodes taken in topological order}
This is critical-path scheduling, and it is the same dynamic programming idea as everywhere else: the topological order is a valid order to fill the table. In a general graph, longest path is NP-hard; the DAG makes it O(V+E)O(V + E).
Python
import heapqdef smallest_order(n, edges):    adj, indeg = [[] for _ in range(n)], [0] * n    for a, b in edges:        adj[a].append(b)        indeg[b] += 1    heap = [u for u in range(n) if indeg[u] == 0]    heapq.heapify(heap)    order = []    while heap:        u = heapq.heappop(heap)          # smallest ready node        order.append(u)        for v in adj[u]:            indeg[v] -= 1            if indeg[v] == 0:                heapq.heappush(heap, v)    return order if len(order) == n else []def rounds(n, edges):    adj, indeg = [[] for _ in range(n)], [0] * n    for a, b in edges:        adj[a].append(b)        indeg[b] += 1    level, count, seen = [u for u in range(n) if indeg[u] == 0], 0, 0    while level:        count, seen = count + 1, seen + len(level)        nxt = []        for u in level:            for v in adj[u]:                indeg[v] -= 1                if indeg[v] == 0:                    nxt.append(v)        level = nxt    return count if seen == n else -1    # -1 means a cyclepipeline = [(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)]print(smallest_order(5, pipeline))       # [0, 1, 2, 3, 4]print(rounds(5, pipeline))               # 4
A min-heap gives the smallest order; counting levels gives the fewest rounds. Pipeline nodes: Load=0, Clean=1, Parse=2, Process=3, Export=4.
Edit and run it in your browser

Patterns

Course schedule, build order, alien dictionary

  • Course schedule

    Pairs [course, prereq]. "Can you finish?" is a cycle check; "give an order" is the sort itself. Mind the edge direction: prereq → course.

  • Build order

    Projects and dependencies. Compile in topological order; a cycle is the "circular dependency" error that make, Gradle and Bazel report.

  • Alien dictionary

    Words sorted in an unknown alphabet. The first differing letter of each adjacent pair gives one edge; sort the letters.

  • Parallel courses

    Minimum semesters when any number of courses can be taken at once: count Kahn's levels.

Alien dictionary: from sorted words to an alphabet

Only the first difference counts: later letters in the same pair tell you nothing.
Python
from collections import dequedef alien_order(words):    adj = {c: set() for w in words for c in w}    indeg = {c: 0 for c in adj}    for a, b in zip(words, words[1:]):        for x, y in zip(a, b):            if x != y:                if y not in adj[x]:                    adj[x].add(y)                    indeg[y] += 1                break        else:            if len(a) > len(b):                return ""                # "abc" listed before "ab"    queue = deque(c for c in indeg if indeg[c] == 0)    out = []    while queue:        c = queue.popleft()        out.append(c)        for d in adj[c]:            indeg[d] -= 1            if indeg[d] == 0:                queue.append(d)    return "".join(out) if len(out) == len(indeg) else ""print(alien_order(["wrt", "wrf", "er", "ett", "rftt"]))   # wertfprint(alien_order(["z", "x", "z"]))                        # "" (cycle)
Every letter that appears is a node, even if it never gets an edge.
Edit and run it in your browser
ProblemDifficultyTechnique
[Course Schedule](https://leetcode.com/problems/course-schedule/) (207)MediumCycle check: Kahn count or three colours
[Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) (210)MediumReturn Kahn's order
[Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) (269)HardEdges from adjacent words, then Kahn
[Parallel Courses](https://leetcode.com/problems/parallel-courses/) (1136)MediumCount Kahn's levels
[Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) (802)MediumKahn on the reversed graph, or three colours
[Build a Matrix With Conditions](https://leetcode.com/problems/build-a-matrix-with-conditions/) (2392)HardTwo independent topological sorts (rows, columns)
Course Schedule, Course Schedule II and Parallel Courses are also in the Practice tab, in our own wording.

Recap

Key takeaways

Key points

  • A topological order lists every node so that each edge u → v has u before v. It exists exactly when the graph is a DAG.
  • Kahn: count in-degrees, queue the zeros, pop and decrement successors, enqueue new zeros. Fewer than V outputs means a cycle.
  • DFS: append each node when it finishes, then reverse. An edge to a GRAY node is a back edge and means a cycle.
  • Three colours are needed in directed graphs: BLACK neighbours (finished elsewhere) are not cycles.
  • Both run in O(V + E) time with O(V) extra space.
  • Orders are rarely unique; check an answer with pos[u] < pos[v] for every edge.
  • Levels of Kahn give the fewest parallel rounds; a min-heap gives the smallest order; DP in topological order solves longest paths.
  • Get the edge direction right first: "a must come before b" is a → b.

Sources