Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Paths in DAGs

Longest paths, critical paths and dynamic programming in topological order.

Longest paths are NP-hard in general graphs, and shortest paths with negative edges need Bellman–Ford's O(nm)O(nm). In a DAG both take one linear pass: relax the edges in topological order. The same pass schedules projects, counts paths, and is exactly what every dynamic program does.

What you’ll learn

  • Prove that relaxing edges in topological order computes single-source shortest and longest paths in a DAG in O(n+m)O(n + m) for any real weights, and explain why the longest simple path is NP-hard in general graphs.
  • Compute earliest starts, latest finishes, slack and critical paths of a project network.
  • Evaluate path counts and other path sums over a semiring in topological order, and handle the overflow that path counts cause.
  • Compute transitive closures and reductions, minimum path covers through matching, and dominator trees, and know the landmark algorithms for each.

Relaxation in topological order

Fix a source ss in a DAG whose edges carry real weights w(u,v)w(u, v), negative ones allowed. Start with d[s]=0d[s] = 0 and d[v]=∞d[v] = \infty for every other vertex, then process the vertices in topological order, relaxing each edge that leaves the current vertex:

d[v]←min⁡(d[v], d[u]+w(u,v))for each edge u→v, with u taken in topological orderd[v] \leftarrow \min\big(d[v],\ d[u] + w(u, v)\big) \quad \text{for each edge } u \to v,\ \text{with } u \text{ taken in topological order}
One relaxation per edge: O(n+m)O(n + m) including the topological sort. Replace min⁡\min by max⁡\max for longest paths.
DerivationProof
  1. d[v]≥δ(s,v)d[v] \ge \delta(s, v)

    Never too small. By induction on the relaxations, every finite d[v]d[v] is the length of some path from ss to vv, so at all times

  2. d[vi]≤δ(s,vi−1)+w(vi−1,vi)=δ(s,vi)d[v_i] \le \delta(s, v_{i-1}) + w(v_{i-1}, v_i) = \delta(s, v_i)

    Exact in time. Let s=v0→v1→⋯→vk=vs = v_0 \to v_1 \to \cdots \to v_k = v be a shortest path. Its edges point forward, so the loop processes v0,v1,…,vkv_0, v_1, \dots, v_k in this order. By induction d[vi−1]=δ(s,vi−1)d[v_{i-1}] = \delta(s, v_{i-1}) when vi−1v_{i-1} is processed, and relaxing its edge to viv_i gives

Acyclicity does two jobs here: it makes shortest and longest paths well defined for any weights (there are finitely many paths and no cycle to go around), and it hands the algorithm an order in which every path's vertices appear. Dijkstra's algorithm has to discover such an order greedily, and that only works with non-negative weights.

Every dynamic program is a DAG. Make each subproblem a vertex, with an edge from every subproblem to each subproblem that uses it. Filling the table in a valid order is processing a topological order, and a minimizing recurrence is a shortest-path relaxation. The Optimal lesson DP as Shortest Paths in a DAG develops this view.

Check your understanding

A directed graph with cycles has positive edge weights. You negate every weight and run Bellman–Ford from ss, hoping to obtain longest simple paths. What happens?

  1. It returns the longest simple paths in O(nm)O(nm)
  2. It works if you run Dijkstra's algorithm instead of Bellman–Ford
  3. Any cycle reachable from ss becomes a negative cycle, and Bellman–Ford reports it instead of distances
  4. It returns longest paths, but only for the vertices that lie on cycles
Show the answer

C. Any cycle reachable from ss becomes a negative cycle, and Bellman–Ford reports it instead of distances

Bellman–Ford computes shortest walks, which exist only when no negative cycle is reachable, and after negation every reachable positive cycle is one. The longest simple path is NP-hard, so no such simple trick can solve it unless P = NP.

Critical paths: scheduling a project

A project is a set of tasks with durations and precedence rules ("EE starts once CC and DD are done"), with as many workers as needed. Make each task a vertex of a DAG, weighted by its duration. Then:

  • The earliest start ES(t)\text{ES}(t) is a longest-path length: the maximum of ES(p)+dur(p)\text{ES}(p) + \text{dur}(p) over the prerequisites pp of tt, or 00 if there are none.
  • The project length TT is the maximum of ES(t)+dur(t)\text{ES}(t) + \text{dur}(t).
  • The latest finish LF(t)\text{LF}(t), computed backward in reverse topological order, is the minimum of LF(q)−dur(q)\text{LF}(q) - \text{dur}(q) over the tasks qq that require tt, or TT if there are none.
  • The slack LF(t)−dur(t)−ES(t)\text{LF}(t) - \text{dur}(t) - \text{ES}(t) is how long tt can slip without delaying the project. The tasks with zero slack form the critical paths, the longest paths of the DAG.
Predict before you look

Tasks, with durations in days: AA 3; BB 6; CC 4, after AA; DD 2, after AA and BB; EE 3, after CC and DD; FF 2, after EE; GG 4, after AA. With unlimited workers, what is the shortest possible project length?

Show the answer

13

The longest chain is B,D,E,FB, D, E, F: 6+2+3+2=136 + 2 + 3 + 2 = 13 days. The chain A,C,E,FA, C, E, F takes 1212 and A,GA, G only 77, so they have slack.

python
from collections import deque

def critical_path(tasks):
    """tasks: {name: (duration, [prerequisites])} -> (length, earliest start, slack)."""
    succ = {t: [] for t in tasks}
    indeg = {t: len(pre) for t, (_, pre) in tasks.items()}
    for t, (_, pre) in tasks.items():
        for p in pre:
            succ[p].append(t)
    order, queue = [], deque(t for t in tasks if indeg[t] == 0)
    while queue:                                    # Kahn's algorithm
        u = queue.popleft()
        order.append(u)
        for v in succ[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    es = {}                                         # forward pass: longest path into t
    for t in order:
        es[t] = max((es[p] + tasks[p][0] for p in tasks[t][1]), default=0)
    length = max(es[t] + tasks[t][0] for t in tasks)
    lf = {}                                         # backward pass: latest finish
    for t in reversed(order):
        lf[t] = min((lf[q] - tasks[q][0] for q in succ[t]), default=length)
    slack = {t: lf[t] - tasks[t][0] - es[t] for t in tasks}
    return length, es, slack

Two linear passes after a topological sort: O(n+m)O(n + m) for nn tasks and mm precedence rules.

TaskDurationRequiresESLFSlack
AA3none041
BB6none060
CC4AA381
DD2AA, BB680
EE3CC, DD8110
FF2EE11130
GG4AA3136
The project takes 13 days and B→D→E→FB \to D \to E \to F is the critical path. AA and CC can each slip 1 day, and GG 6 days.

To finish sooner you must shorten critical tasks: speeding up GG changes nothing, and when several critical paths exist, all of them must shrink. Choosing which tasks to speed up at least cost ("crashing" the project) is a linear program.

Counting paths and other path sums

The relaxation loop used nothing special about min⁡\min and ++. Replace them by any two operations that form a semiring: ⊕\oplus combines alternative paths, ⊗\otimes extends a path by one edge, and ⊗\otimes distributes over ⊕\oplus. Processing the vertices in topological order then computes, for every vv, the ⊕\oplus-sum over all paths from ss to vv of the ⊗\otimes-product of their edge values, with O(n+m)O(n + m) semiring operations. This is the algebraic path problem, and on a DAG it is always easy, because there are finitely many paths and no cycles to sum around.

Question⊕\oplus (alternatives)⊗\otimes (along a path)Edge valueValue at ss
Shortest pathmin⁡\min++w(u,v)w(u, v)00
Longest pathmax⁡\max++w(u,v)w(u, v)00
Number of paths++×\times1111
Is vv reachable?orandtruetrue
Widest path (largest bottleneck)max⁡\maxmin⁡\mincapacity c(u,v)c(u, v)+∞+\infty
On graphs with cycles these sums range over infinitely many walks, which is why general graphs need Dijkstra's algorithm, Bellman–Ford or Floyd–Warshall instead of a single pass.
Check your understanding

To count the shortest paths from ss in a weighted DAG, keep d[v]d[v] and cnt[v]\text{cnt}[v]. When relaxing u→vu \to v finds d[u]+w(u,v)=d[v]d[u] + w(u, v) = d[v] exactly, what should happen?

  1. Nothing, since d[v]d[v] does not change
  2. cnt[v]←cnt[v]+1\text{cnt}[v] \leftarrow \text{cnt}[v] + 1
  3. cnt[v]←cnt[u]\text{cnt}[v] \leftarrow \text{cnt}[u]
  4. cnt[v]←cnt[v]+cnt[u]\text{cnt}[v] \leftarrow \text{cnt}[v] + \text{cnt}[u]
Show the answer

D. cnt[v]←cnt[v]+cnt[u]\text{cnt}[v] \leftarrow \text{cnt}[v] + \text{cnt}[u]

A tie means that every shortest path to uu, extended by u→vu \to v, is another shortest path to vv, so their number is added. A strict improvement resets instead: d[v]←d[u]+w(u,v)d[v] \leftarrow d[u] + w(u, v) and cnt[v]←cnt[u]\text{cnt}[v] \leftarrow \text{cnt}[u]. This is the semiring of (distance, count) pairs.

Reachability structure: closure, covers and dominators

Transitive closure. Process the vertices in reverse topological order and set reach[u]={u}∪⋃u→vreach[v]\text{reach}[u] = \{u\} \cup \bigcup_{u \to v} \text{reach}[v]. Stored as bitsets of nn bits, each edge costs one OR of n/wn / w machine words: O(nm/w)O(nm / w) time and O(n2/w)O(n^2 / w) words of memory on a word RAM with ww-bit words. For graphs with cycles, first collapse each strongly connected component, whose vertices all reach the same set.

Transitive reduction. Aho, Garey and Ullman (1972) showed that a DAG has a unique smallest graph with the same reachability: keep u→vu \to v exactly when no other path leads from uu to vv. In A→BA \to B, A→CA \to C, A→DA \to D, B→DB \to D, C→DC \to D, the edge A→DA \to D is implied and is dropped. They also showed that the reduction costs the same as the closure, up to constant factors. With cycles, the smallest subgraph with the same reachability is NP-hard to find: a strongly connected graph has one with nn edges exactly when it has a Hamiltonian cycle.

Minimum path cover. To cover every vertex with as few vertex-disjoint paths as possible, split each vertex vv into voutv^{\text{out}} and vinv^{\text{in}}, and join uoutu^{\text{out}} to vinv^{\text{in}} for every edge u→vu \to v. A matching in this bipartite graph links paths end to start, each matched edge merging two paths into one, so the minimum number of paths is nn minus the size of a maximum matching. If the paths may share vertices, run the same construction on the transitive closure: this is Fulkerson's (1956) constructive proof of Dilworth's theorem (1950), which says that the fewest chains covering a partial order equal the size of its largest antichain.

For general flow graphs, with cycles, Lengauer and Tarjan (1979) compute dominators in O(mlog⁡n)O(m \log n) with a simple version and O(m α(m,n))O(m\,\alpha(m, n)) with a sophisticated one, where α\alpha is the inverse Ackermann function; Alstrup, Harel, Lauridsen and Thorup (1999) reached linear time.

Check your understanding

In the DAG with edges s→as \to a, s→bs \to b, a→ca \to c, b→cb \to c and c→dc \to d, which vertices other than dd lie on every path from ss to dd?

  1. Only cc
  2. Only ss
  3. ss and cc
  4. ss, aa, bb and cc
Show the answer

C. ss and cc

idom(c)\text{idom}(c) is the lowest common ancestor of aa and bb, which is ss; and cc is the only predecessor of dd, so idom(d)=c\text{idom}(d) = c. The dominators of dd are therefore ss, cc and dd itself. Neither aa nor bb is on every path: each one can be bypassed through the other.

Key takeaways

  • In a DAG, relaxing edges in topological order gives single-source shortest or longest paths in O(n+m)O(n + m) for any real weights; in general graphs the longest simple path is NP-hard.
  • The critical path method runs a forward pass of longest paths for earliest starts and a backward pass for latest finishes; slack is LF−dur−ES\text{LF} - \text{dur} - \text{ES}, and the zero-slack tasks form the critical paths.
  • The same loop computes any path sum over a semiring, such as path counts, reachability or widest paths; counts grow exponentially, so use modular, big-integer or saturating arithmetic.
  • Bitset closure costs O(nm/w)O(nm / w); a DAG's transitive reduction is unique (Aho, Garey & Ullman, 1972); a minimum path cover has nn minus a maximum matching paths; dominators of a DAG are LCAs of predecessors, and Lengauer–Tarjan handles general graphs.

Check yourself

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

Question 1

Why does relaxing edges in topological order give correct shortest paths in a DAG with negative weights, where Dijkstra's algorithm can fail?

  1. Because a DAG cannot contain negative edges in the first place
  2. Because each vertex is processed only after every edge into it has been relaxed, so its distance is already final
  3. Because topological order processes vertices by increasing distance
  4. Because each vertex is relaxed n−1n - 1 times, as in Bellman–Ford
Show the answer

B. Because each vertex is processed only after every edge into it has been relaxed, so its distance is already final

Every path's vertices appear in topological order, so all edges into vv are relaxed before vv is used, whatever their signs. Dijkstra's algorithm instead assumes that the smallest tentative distance is final, which a later negative edge can contradict.

Question 2

In the example project, task GG (slack 6 days) is delayed by 4 days. What happens to the project length of 13 days?

  1. It grows to 17 days
  2. It grows to 15 days
  3. It stays at 13 days
  4. It grows to 14 days
Show the answer

C. It stays at 13 days

Slack is exactly how long a task can slip without moving the end date. A 4-day delay uses 4 of GG's 6 days, so GG now ends on day 11, still before 13. A 7-day delay would push the project to 14 days.

Question 3

A DAG has 10 vertices, and a maximum matching in its split bipartite graph (an edge uout–vinu^{\text{out}}\text{–}v^{\text{in}} for each edge u→vu \to v) has 7 edges. What is the minimum number of vertex-disjoint paths that cover every vertex?

  1. 3
  2. 7
  3. 10
  4. 17
Show the answer

A. 3

Start with 10 one-vertex paths; each matched edge links the end of one path to the start of another, merging two paths into one. With 7 merges, 10−7=310 - 7 = 3 paths remain, and a smaller cover would give a larger matching.

Question 4

You compute the transitive closure of a DAG with n=20,000n = 20{,}000 vertices and m=100,000m = 100{,}000 edges, using bitsets of 64-bit words in reverse topological order. About how many word operations does it take?

  1. About 3×1073 \times 10^{7}
  2. About 4×1084 \times 10^{8}
  3. About 2×1092 \times 10^{9}
  4. About 8×10128 \times 10^{12}
Show the answer

A. About 3×1073 \times 10^{7}

Each edge ORs one bitset of n/64≈313n / 64 \approx 313 words into another: nm/64≈3.1×107nm / 64 \approx 3.1 \times 10^{7} word operations, a fraction of a second. The memory, n2n^2 bits =50= 50 MB, is the real limit.

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §22.2 on shortest paths in DAGs.
  • J. E. Kelley & M. R. Walker, "Critical-path planning and scheduling," Proceedings of the Eastern Joint Computer Conference (1959).
  • A. V. Aho, M. R. Garey & J. D. Ullman, "The transitive reduction of a directed graph," SIAM Journal on Computing 1(2) (1972), 131–137.
  • T. Lengauer & R. E. Tarjan, "A fast algorithm for finding dominators in a flowgraph," ACM Transactions on Programming Languages and Systems 1(1) (1979), 121–141.
  • S. Alstrup, D. Harel, P. W. Lauridsen & M. Thorup, "Dominators in linear time," SIAM Journal on Computing 28(6) (1999), 2117–2132.