Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

DAGs, Topological Sort & Strong Connectivity

Ordering dependencies, finding cycles and condensing a directed graph.

A build system, a spreadsheet and a package manager all answer the same question thousands of times a day: given rules of the form "X must come before Y", find an order that obeys every rule, or prove that none exists. One linear-time pass does both, and the depth-first search behind it also splits any directed graph into strongly connected pieces arranged in a DAG.

What you’ll learn

  • Prove that a directed graph has a topological order if and only if it has no directed cycle.
  • Compute a topological order with Kahn's algorithm or with DFS finishing times in O(n+m)O(n + m), detect cycles with each, and find the lexicographically smallest order with a min-heap.
  • Define strongly connected components, prove that the condensation is a DAG, and outline Kosaraju's and Tarjan's linear-time algorithms.
  • Compute longest paths and path counts in a DAG by dynamic programming in topological order.
  • Recognize prerequisite, build-order and scheduling problems as DAG problems, and avoid their classic bugs.

Orders that respect every arrow

In a directed graph an edge u→vu \to v often means "uu must happen before vv": a course before the course that requires it, a source file before the files that import it, a spreadsheet cell before the formulas that read it. A topological order lists all nn vertices so that every edge points forward: whenever u→vu \to v is an edge, uu comes before vv.

Such an order does not always exist. If AA requires BB and BB requires AA, no schedule works. The obstacle is always a directed cycle, and the graphs without one have their own name: directed acyclic graphs, or DAGs.

DerivationProof
  1. π(v1)<π(v2)<⋯<π(vk)<π(v1),a contradiction.\pi(v_1) < \pi(v_2) < \cdots < \pi(v_k) < \pi(v_1),\quad\text{a contradiction.}

    A cycle blocks every order. Suppose v1→v2→⋯→vk→v1v_1 \to v_2 \to \cdots \to v_k \to v_1 is a cycle and π(v)\pi(v) is the position of vv in a topological order. Every edge points forward, so

  2. v0←v1←⋯←vn⟹vi=vj for some i<j≤nv_0 \leftarrow v_1 \leftarrow \cdots \leftarrow v_n \quad\Longrightarrow\quad v_i = v_j \text{ for some } i < j \le n

    Every nonempty DAG has a source, a vertex with no incoming edge. Otherwise, start anywhere and keep stepping backward along incoming edges. After nn steps some vertex has repeated, and the walk between the two visits, read forward, is a directed cycle:

  3. order(G)=s, order(G−s)\text{order}(G) = s,\ \text{order}(G - s)

    Peel off a source. Put a source ss first and delete it. Deleting a vertex cannot create a cycle, so what remains is a DAG on n−1n - 1 vertices; by induction it has a topological order, and ss followed by that order is a topological order of the whole graph:

Think first How many topological orders does a DAG on nn vertices with no edges have? And a single path v1→v2→⋯→vnv_1 \to v_2 \to \cdots \to v_n?

n!n! and exactly 11. Other DAGs fall in between, and counting their orders exactly is #P\#\mathrm{P}-complete (Brightwell & Winkler, 1991), even though finding one order takes linear time. Whenever a problem wants one particular order, it must say which, for example the lexicographically smallest.

Kahn’s algorithm: peel off the sources

The proof is an algorithm. Keep a counter indeg[v]\text{indeg}[v] of the edges into vv not yet removed, and a queue of the vertices whose counter is 00: they are ready. Repeatedly take a ready vertex, output it, and remove its outgoing edges by decrementing its out-neighbors' counters; a vertex joins the queue the moment its counter reaches 00. This is Kahn's algorithm (1962).

python
from collections import deque

def topo_order(n, edges):
    """Kahn's algorithm: a topological order of 0..n-1, or None if there is a cycle."""
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:
        adj[u].append(v)
        indeg[v] += 1
    queue = deque(v for v in range(n) if indeg[v] == 0)
    order = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:          # v's last prerequisite is done
                queue.append(v)
    return order if len(order) == n else None   # leftovers: a cycle blocks them

Each vertex enters and leaves the queue once and each edge is examined once: O(n+m)O(n + m) time and memory with adjacency lists. Vertices that appear in no edge start ready and are output too.

Cycle detection comes free. If the queue empties while vertices remain, those leftovers can never become ready: each one still has an incoming edge from another leftover. Walking backward along such edges stays among the leftovers, so it must repeat a vertex and close a cycle. Conversely, the vertices of a cycle block each other forever. So Kahn's algorithm outputs all nn vertices if and only if the graph is a DAG.

Check your understanding

Kahn's algorithm runs on a directed graph and stops with three vertices never output. Which statement must be true?

  1. Each of the three vertices lies on a directed cycle
  2. The leftovers contain a directed cycle, and every leftover vertex lies on a cycle or can be reached from one
  3. The graph is a DAG, but the algorithm started from the wrong vertex
  4. The graph has exactly one directed cycle
Show the answer

B. The leftovers contain a directed cycle, and every leftover vertex lies on a cycle or can be reached from one

Every leftover vertex keeps an incoming edge from another leftover, so walking backward from any of them stays among the leftovers and closes a cycle: each leftover lies on a cycle or downstream of one. In the graph E→A→BE \to A \to B, B→CB \to C, C→BC \to B, C→DC \to D, Kahn's algorithm outputs E,AE, A and leaves B,C,DB, C, D, but only BB and CC lie on the cycle.

Depth-first search: reverse finishing order

The second classic method needs no counters. Run a depth-first search from every unvisited vertex and record each vertex when it finishes, that is, once everything reachable from it has been explored. Then output the vertices in reverse order of finishing time f[v]f[v]. Color the vertices white (unseen), gray (on the recursion stack) and black (finished).

DerivationProof
  1. f[v]<f[u]f[v] < f[u]

    Consider the moment DFS scans the edge u→vu \to v; then uu is gray. If vv is white, vv becomes a descendant of uu and finishes first:

  2. f[v]<f[u]f[v] < f[u]

    If vv is black, it has already finished, while uu is still running:

  3. v⇝u→vv \rightsquigarrow u \to v

    If vv is gray, it is an ancestor of uu on the recursion stack, so the tree path from vv to uu plus the edge u→vu \to v is a directed cycle. In a DAG this case cannot happen, which proves the first claim and half of the second:

  4. u→v is scanned while v is grayu \to v \text{ is scanned while } v \text{ is gray}

    Every cycle produces a back edge. Let vv be the first vertex of a cycle that DFS discovers. At that moment the rest of the cycle is white and reachable from vv through white vertices, so all of it becomes a descendant of vv, including the vertex uu just before vv on the cycle. When DFS scans u→vu \to v, the search of vv has not finished:

python
import sys

def topo_dfs(n, adj):
    """Reverse postorder of a depth-first search; None if a back edge closes a cycle."""
    sys.setrecursionlimit(10_000 + 2 * n)
    color = [0] * n            # 0 white (unseen), 1 gray (on the stack), 2 black (finished)
    post = []
    def visit(u):
        color[u] = 1
        for v in adj[u]:
            if color[v] == 1 or (color[v] == 0 and not visit(v)):
                return False   # a back edge u -> v closes a cycle
        color[u] = 2
        post.append(u)         # u finishes after everything it can reach
        return True
    for s in range(n):
        if color[s] == 0 and not visit(s):
            return None
    return post[::-1]

O(n+m)O(n + m). Looping over every start vertex covers graphs that are not reachable from one place. Python's default recursion limit is 1,000 frames, so the code raises it; for very deep inputs, such as a chain of 10610^6 prerequisites, prefer Kahn's algorithm or an explicit stack.

Which order? The two methods usually output different orders, both valid. When a problem wants a particular one, say the lexicographically smallest, choose it explicitly: in Kahn's algorithm always take the smallest ready vertex, with a min-heap instead of a queue, for O((n+m)log⁡n)O((n + m)\log n) time. The greedy choice is safe because the vertex placed next must be ready, and every ready vertex can be extended to a full order. DFS with sorted neighbors does not do this: with vertices 1,2,31, 2, 3 and the single edge 3→13 \to 1, the smallest order is 2,3,12, 3, 1, but reverse finishing order from a DFS that starts at 11 gives 3,2,13, 2, 1.

cpp
#include <cstdio>
#include <functional>
#include <queue>
#include <vector>
using namespace std;

int main() {
    int n, m;
    if (scanf("%d %d", &n, &m) != 2) return 0;
    vector<vector<int>> adj(n + 1);
    vector<int> indeg(n + 1, 0);
    for (int i = 0; i < m; i++) {
        int u, v;
        if (scanf("%d %d", &u, &v) != 2) return 0;
        adj[u].push_back(v);
        indeg[v]++;
    }
    priority_queue<int, vector<int>, greater<int>> ready;  // min-heap of available vertices
    for (int v = 1; v <= n; v++)
        if (indeg[v] == 0) ready.push(v);
    vector<int> order;
    while (!ready.empty()) {
        int u = ready.top();
        ready.pop();
        order.push_back(u);
        for (int v : adj[u])
            if (--indeg[v] == 0) ready.push(v);
    }
    if ((int)order.size() < n) { puts("IMPOSSIBLE"); return 0; }
    for (int i = 0; i < n; i++) printf("%d%c", order[i], i + 1 < n ? ' ' : '\n');
}

Contest style: vertices 1,…,n1, \dots, n, then the mm edges. A priority_queue with greater<int> is a min-heap; with a plain queue the same loop is Kahn's algorithm in O(n+m)O(n + m).

Strongly connected components and the condensation

A graph with cycles still has structure. Call uu and vv strongly connected if each can reach the other. The relation is reflexive, symmetric and transitive, so it splits the vertices into classes, the strongly connected components (SCCs). Inside a component every vertex reaches every other; between two components, reachability goes one way at most.

So every directed graph is a DAG of strongly connected pieces: a plain DAG when every piece is one vertex, strongly connected when there is a single piece. Two classic linear-time algorithms find the pieces, both built on DFS:

AlgorithmHow it worksOrder of the components found
Kosaraju–Sharir (Kosaraju 1978, unpublished; Sharir 1981)DFS on GG records finishing times. A second DFS runs on the reversed graph GRG^{R}, always starting from the unvisited vertex that finished last; each search tree of this pass is one SCC.Topological order of the condensation (sources first)
Tarjan (1972)One DFS keeps a stack of vertices and a low-link value low[v]\text{low}[v]: the smallest discovery time of a vertex still on the stack that vv's subtree can reach with one extra edge. When low[v]=d[v]\text{low}[v] = d[v], vv is the first vertex of its component, which is popped off the stack.Reverse topological order (sinks first)
Both take O(n+m)O(n + m) time. Kosaraju's needs the reversed graph and two passes; Tarjan's needs one pass and is usually faster in practice.
Think first Why does Kosaraju's second pass run on the reversed graph? What would a search in GG itself, started from the vertex that finished last, collect?

The last finisher lies in a source component of the condensation, and from a source component much of the graph is usually reachable: a search in GG would sweep up every component downstream of it. Reversing every edge turns that source component into a sink, so a search there in GRG^{R} cannot leave it and collects exactly one SCC. With that component removed, the latest remaining finisher again lies in a sink of what is left of GRG^{R}, and so on. The Optimal lesson proves this lemma about finishing times.

Applications are everywhere: a cycle in a "wait-for" graph of processes is a deadlock; compilers find loops as SCCs of a program's control-flow graph; reachability and model-checking tools collapse each SCC to one node before doing anything else; and the 2-SAT algorithm decides a Boolean formula by computing the SCCs of its implication graph.

Dynamic programming on a DAG

A topological order is exactly the order a dynamic program needs: by the time vertex vv is processed, every edge into vv has been considered. One pass over the vertices computes, from a source ss, the longest or shortest path to every vertex (negative weights are fine), the number of distinct paths, or the earliest time each task of a project can start.

best[v]=max⁡u→v(best[u]+w(u,v)),ways[v]=∑u→vways[u]\text{best}[v] = \max_{u \to v}\big(\text{best}[u] + w(u, v)\big), \qquad \text{ways}[v] = \sum_{u \to v} \text{ways}[u]
Process vv in topological order, starting from best[s]=0\text{best}[s] = 0 and ways[s]=1\text{ways}[s] = 1; vertices that ss cannot reach keep −∞-\infty and 00.
python
def dag_paths(n, edges, order, s):
    """Longest path length and number of paths from s to every vertex of a DAG."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    best = [float('-inf')] * n
    ways = [0] * n
    best[s], ways[s] = 0, 1
    for u in order:                  # every edge into v is relaxed before v is used
        for v, w in adj[u]:
            best[v] = max(best[v], best[u] + w)
            ways[v] += ways[u]
    return best, ways

O(n+m)O(n + m) given a topological order. Replace max with min for shortest paths. Python integers never overflow, but in C++ path counts outgrow 64 bits quickly, which is why problems ask for them modulo a prime.

Predict before you look

Six courses: PP and MM have no prerequisites, DD requires both PP and MM, AA and OO each require DD, and CC requires AA. You may take any number of courses per semester. What is the minimum number of semesters?

Show the answer

4

The answer is the number of vertices on a longest path. P→D→A→CP \to D \to A \to C has four, so four semesters are necessary, and taking every course as soon as its prerequisites are done achieves four: {P,M}\{P, M\}, {D}\{D\}, {A,O}\{A, O\}, {C}\{C\}. These are the "layers" of Kahn's algorithm when it removes all ready vertices at once.

Recognizing it

Signals. "Prerequisites", "depends on", "must come before", "build order", "is a valid schedule possible?", or any process that only moves forward (a recipe, versions of a file, moves on a grid that only go right or down). "Each can reach the other", "mutually reachable" or "groups that cannot be separated" point to SCCs. Constraints of 10510^5 to 10610^6 vertices and edges call for a linear-time pass.

Problem (in our words)Key ideaTime
Can every course be finished, given the prerequisite pairs?Kahn's algorithm: feasible if and only if all nn vertices are outputO(n+m)O(n + m)
Recover the letter order of an alien alphabet from a sorted list of wordsCompare neighboring words: their first differing letters give an edge; then sort the letters topologically. A word followed by its own proper prefix, or a cycle, means no alphabet fitsO(L+σ)O(L + \sigma) for total length LL and alphabet size σ\sigma
Fewest semesters with unlimited courses per semesterLongest path counted in vertices: the number of Kahn layersO(n+m)O(n + m)
The smallest-numbered valid orderKahn's algorithm with a min-heapO((n+m)log⁡n)O((n + m)\log n)
Fewest new edges so that every vertex can reach every otherCompute the SCCs; if the condensation has k≥2k \ge 2 vertices, aa sources and bb sinks, the answer is max⁡(a,b)\max(a, b) (Eswaran & Tarjan, 1976)O(n+m)O(n + m)
Classic interview and contest problems. The last row is a theorem, not a greedy guess.

Common bugs.

  • Reversed arrows: "vv requires uu" is the edge u→vu \to v.
  • Reporting a cycle at any visited vertex instead of at a gray one.
  • Forgetting isolated vertices, which appear in no edge but still belong in the order.
  • Recursion depth: a chain of 10510^5 prerequisites overflows a default recursion limit or a small C++ stack.
  • Using the order before checking that all nn vertices made it into it.
Check your understanding

A build has 2⋅1052 \cdot 10^5 steps and 5⋅1055 \cdot 10^5 dependencies "step uu must run before step vv". Output a valid order, or, if the dependencies are circular, report one circular chain of steps. Which technique fits?

  1. Dijkstra's algorithm from every step that has no dependencies
  2. Union-find over the dependency pairs, reporting a cycle when two steps already share a set
  3. DFS with white, gray and black: reverse finishing order, and at an edge into a gray vertex, read the cycle off the recursion stack
  4. Backtracking over orders of the steps, checking each against the dependencies
Show the answer

C. DFS with white, gray and black: reverse finishing order, and at an edge into a gray vertex, read the cycle off the recursion stack

DFS gives the order in O(n+m)O(n + m), and when it scans an edge u→vu \to v into a gray vertex, the gray vertices from vv down to uu on the stack are the cycle to report. Kahn's algorithm also decides feasibility, but it only tells you which vertices are blocked; extracting a cycle from the leftovers takes one more walk.

Key takeaways

  • A directed graph has a topological order if and only if it is a DAG. Kahn's algorithm (repeatedly remove a vertex of in-degree 0) and reverse DFS finishing order both find one in O(n+m)O(n + m).
  • Kahn's algorithm exposes a cycle as leftover vertices; DFS exposes one as an edge into a gray vertex, never merely a visited one.
  • The lexicographically smallest order comes from Kahn's algorithm with a min-heap, in O((n+m)log⁡n)O((n + m)\log n).
  • Strongly connected components partition every directed graph, and the condensation is a DAG; Kosaraju's and Tarjan's algorithms find the components in linear time.
  • Dynamic programming in topological order computes longest paths, path counts and schedules in O(n+m)O(n + m); on graphs with cycles, the longest simple path is NP-hard.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

DFS runs on a DAG, with discovery times d[⋅]d[\cdot] and finishing times f[⋅]f[\cdot]. For an edge u→vu \to v, which statement always holds?

  1. d[u]<d[v]d[u] < d[v]
  2. f[u]>f[v]f[u] > f[v]
  3. f[u]<f[v]f[u] < f[v]
  4. d[u]<d[v]d[u] < d[v] and f[u]>f[v]f[u] > f[v]
Show the answer

B. f[u]>f[v]f[u] > f[v]

Whether vv is white or black when the edge is scanned, it finishes before uu; it cannot be gray in a DAG. That is exactly why decreasing finishing time is a topological order.

Question 2

You need the lexicographically smallest topological order of the vertices 1,…,n1, \dots, n. Which method is correct?

  1. Kahn's algorithm with a min-heap of ready vertices
  2. DFS visiting neighbors in increasing order, then reversing the finishing order
  3. Kahn's algorithm with a first-in, first-out queue initialized in increasing order
  4. Sort the vertices by in-degree, breaking ties by number
Show the answer

A. Kahn's algorithm with a min-heap of ready vertices

Position by position, the next vertex must be ready, and the smallest ready vertex can always be extended to a full order, so taking it is optimal. A min-heap gives O((n+m)log⁡n)O((n + m)\log n).

Question 3

A DFS cycle check marks vertices as visited and reports a cycle whenever it meets a visited vertex. On which graph does it report a cycle that does not exist?

  1. A→BA \to B, B→CB \to C
  2. A→BA \to B, B→CB \to C, C→AC \to A
  3. A→BA \to B, A→CA \to C, C→BC \to B
  4. A→BA \to B, B→AB \to A
Show the answer

C. A→BA \to B, A→CA \to C, C→BC \to B

Whichever of BB and CC the search from AA explores first, it later meets the finished vertex BB again, through C→BC \to B or through A→BA \to B. That vertex is black, not gray: the graph is a DAG. Only an edge into a gray vertex proves a cycle.

Question 4

Count the paths from ss to tt in a DAG with 10510^5 vertices and 3⋅1053 \cdot 10^5 edges, modulo 109+710^9 + 7. What is the right approach?

  1. Enumerate every path with DFS and count those that end at tt
  2. BFS from ss, counting how many times tt is reached
  3. Run Dijkstra's algorithm and count shortest paths
  4. Dynamic programming in topological order: ways[v]\text{ways}[v] is the sum of ways[u]\text{ways}[u] over the edges u→vu \to v
Show the answer

D. Dynamic programming in topological order: ways[v]\text{ways}[v] is the sum of ways[u]\text{ways}[u] over the edges u→vu \to v

Every path into vv arrives through exactly one last edge u→vu \to v, so the counts add up, and a topological order makes each ways[u]\text{ways}[u] final before it is used: O(n+m)O(n + m) in total. The counts themselves can be astronomically large, so they are reduced modulo the prime as they are added.

Go deeper

Further reading

  • A. B. Kahn, "Topological sorting of large networks," Communications of the ACM 5(11) (1962), 558–562.
  • R. E. Tarjan, "Depth-first search and linear graph algorithms," SIAM Journal on Computing 1(2) (1972), 146–160.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 20.
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), §4.2 "Directed Graphs".