Skip to lesson

Shortest and longest paths in a DAG

Directed acyclic graphs allow single-source shortest and longest paths to be solved in linear O(V + E) time.

Linear time shortest paths via topological ordering

General graphs require O((V + E) log V) time with Dijkstra or O(V * E) with Bellman-Ford. Cycles force algorithms to maintain priority queues or run repeated relaxation passes. In a Directed Acyclic Graph (DAG), the absence of cycles enables a far faster approach.

Topological order shortest path relaxation

Step 1 of 4

324-15ABCD
distA
0
distB
inf
distC
inf
distD
inf
Topological ordering [A, B, C, D]. Set dist[A] = 0, all others infinity.

Example 1 · Brute force: Bellman-Ford on a DAG, O(V * E)

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int n = 4;        int INF = 1_000_000_000;        int[][] edges = {{0, 1, 3}, {0, 2, 2}, {2, 1, -1}, {1, 3, 4}, {2, 3, 5}};        int[] dist = new int[n];        Arrays.fill(dist, INF);        dist[0] = 0;
        for (int round = 0; round < n - 1; round++) {      // V - 1 full passes            for (int[] e : edges) {                if (dist[e[0]] != INF && dist[e[0]] + e[2] < dist[e[1]]) {                    dist[e[1]] = dist[e[0]] + e[2];                }            }        }        System.out.println("Distances from 0: " + Arrays.toString(dist));    }}
Output
Distances from 0: [0, 1, 2, 5]

What this code does

  • Bellman-Ford handles the negative edge, but it does V - 1 passes over all E edges.
  • On a DAG, a topological order lets each edge be relaxed exactly once, in the right order.
  • That drops the cost to O(V + E).

Example 2 · Optimal: relax in topological order, O(V + E) time

DagShortestPathDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import java.util.Queue;
public class DagShortestPathDemo {    public static final int INF = 1_000_000_000;
    static class Edge {        int to, weight;        Edge(int to, int weight) { this.to = to; this.weight = weight; }    }
    public static int[] shortestPathDAG(int n, List<List<Edge>> adj, int src) {        int[] inDegree = new int[n];        for (int u = 0; u < n; u++) {            for (Edge e : adj.get(u)) inDegree[e.to]++;        }
        Queue<Integer> q = new LinkedList<>();        for (int i = 0; i < n; i++) if (inDegree[i] == 0) q.offer(i);
        List<Integer> topo = new ArrayList<>();        while (!q.isEmpty()) {            int u = q.poll();            topo.add(u);            for (Edge e : adj.get(u)) {                if (--inDegree[e.to] == 0) q.offer(e.to);            }        }
        int[] dist = new int[n];        Arrays.fill(dist, INF);        dist[src] = 0;
        for (int u : topo) {            if (dist[u] != INF) {                for (Edge e : adj.get(u)) {                    if (dist[u] + e.weight < dist[e.to]) {                        dist[e.to] = dist[u] + e.weight;                    }                }            }        }        return dist;    }
    public static void main(String[] args) {        int n = 4;        List<List<Edge>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        adj.get(0).add(new Edge(1, 3));        adj.get(0).add(new Edge(2, 2));        adj.get(2).add(new Edge(1, -1));        adj.get(1).add(new Edge(3, 4));        adj.get(2).add(new Edge(3, 5));
        int[] dist = shortestPathDAG(n, adj, 0);        System.out.println("Distances from 0: " + Arrays.toString(dist));    }}
Output
Distances from 0: [0, 1, 2, 5]

What this code does

  • Computes topological sort order [0, 2, 1, 3] using in-degree reduction.
  • Relaxes edges in exact topological order, handling negative edge (2, 1, -1) cleanly.
  • Achieves optimal linear O(V + E) time without requiring a PriorityQueue.
  • In topological order, every edge is relaxed once after its start vertex is final, so V - 1 passes are not needed.

A topological sort orders vertices so every directed edge points strictly forward. When we process vertex u in topological order, all edges leading into u have already been explored. No future vertex can ever loop back to offer a shorter route to u. Therefore, dist[u] is permanently finalised before we relax its outgoing edges. Finding a topological sort takes linear O(V + E) time using Kahn's algorithm or DFS. Relaxing outgoing edges across all vertices in topological order takes O(V + E) time. This drops the total runtime to pure linear O(V + E) time. Crucially, this method works correctly even when edge weights are negative.

Order of execution

Relax in topological order

The distances are set up. Tap the remaining steps in order.

Longest paths in a DAG: trivial here, NP-hard elsewhere

Finding the longest simple path in a general graph is NP-hard. There is no known polynomial-time algorithm for general longest paths. In a DAG, however, the longest path problem is easily solved in linear time.

Example 3 · Longest Path in a DAG

DagLongestPathDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import java.util.Queue;
public class DagLongestPathDemo {    public static final int NEG_INF = -1_000_000_000;
    static class Edge {        int to, weight;        Edge(int to, int weight) { this.to = to; this.weight = weight; }    }
    public static int longestPath(int n, List<List<Edge>> adj, int src, int target) {        int[] inDegree = new int[n];        for (int u = 0; u < n; u++) {            for (Edge e : adj.get(u)) inDegree[e.to]++;        }
        Queue<Integer> q = new LinkedList<>();        for (int i = 0; i < n; i++) if (inDegree[i] == 0) q.offer(i);
        List<Integer> topo = new ArrayList<>();        while (!q.isEmpty()) {            int u = q.poll();            topo.add(u);            for (Edge e : adj.get(u)) {                if (--inDegree[e.to] == 0) q.offer(e.to);            }        }
        int[] dist = new int[n];        Arrays.fill(dist, NEG_INF);        dist[src] = 0;
        for (int u : topo) {            if (dist[u] != NEG_INF) {                for (Edge e : adj.get(u)) {                    if (dist[u] + e.weight > dist[e.to]) {                        dist[e.to] = dist[u] + e.weight;                    }                }            }        }        return dist[target];    }
    public static void main(String[] args) {        int n = 4;        List<List<Edge>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        adj.get(0).add(new Edge(1, 4));        adj.get(1).add(new Edge(3, 5));        adj.get(0).add(new Edge(2, 2));        adj.get(2).add(new Edge(3, 6));
        int maxLen = longestPath(n, adj, 0, 3);        System.out.println("Longest path from 0 to 3: " + maxLen);    }}
Output
Longest path from 0 to 3: 9

What this code does

  • Initialises tentative distances to negative infinity and source to 0.
  • Updates dist[v] = max(dist[v], dist[u] + weight) in topological order.
  • Identifies path 0 -> 1 -> 3 of total weight 4 + 5 = 9 as the longest path.

To find the longest path, initialise all tentative distances to negative infinity. Set the source distance to 0, then process vertices in topological order. When relaxing edge u->v, take the maximum: dist[v] = max(dist[v], dist[u] + weight). Because every path in a DAG is acyclic, infinite looping is impossible. Consider three tasks: S->A of length 4, A->B of length 5, and S->B of length 7. Processing in topological order yields dist[A] = 4. At vertex B, max(7, 4 + 5) equals 9, choosing the composite path. The longest path of length 9 finishes in linear O(V + E) time.

Critical Path Method in project scheduling

Project management frequently models dependencies as directed acyclic networks. Vertices or edges represent tasks, and weights denote task completion durations. The critical path is the longest path from project start to project finish.

Example 4 · Critical Path Method for Project Scheduling

CriticalPathDemo.javaJava
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;
public class CriticalPathDemo {    public static int projectDuration(int n, int[] duration, int[][] dependencies) {        List<List<Integer>> adj = new ArrayList<>();        int[] inDegree = new int[n];        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int[] dep : dependencies) {            int prev = dep[0];            int next = dep[1];            adj.get(prev).add(next);            inDegree[next]++;        }
        int[] earliestFinish = new int[n];        Queue<Integer> q = new LinkedList<>();        for (int i = 0; i < n; i++) {            if (inDegree[i] == 0) {                earliestFinish[i] = duration[i];                q.offer(i);            }        }
        int maxProjectTime = 0;        while (!q.isEmpty()) {            int u = q.poll();            maxProjectTime = Math.max(maxProjectTime, earliestFinish[u]);            for (int v : adj.get(u)) {                earliestFinish[v] = Math.max(earliestFinish[v], earliestFinish[u] + duration[v]);                if (--inDegree[v] == 0) {                    q.offer(v);                }            }        }        return maxProjectTime;    }
    public static void main(String[] args) {        // 4 tasks with durations: [3, 2, 4, 2]        int[] duration = {3, 2, 4, 2};        // 0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3        int[][] deps = {{0, 1}, {0, 2}, {1, 3}, {2, 3}};        int time = projectDuration(4, duration, deps);        System.out.println("Critical project duration: " + time);    }}
Output
Critical project duration: 9

What this code does

  • Models tasks with duration as node weights and prerequisite rules as directed edges.
  • Propagates earliest finish times along topological order using max aggregation.
  • Critical path 0 -> 2 -> 3 requires 3 + 4 + 2 = 9 time units to complete.

Any delay in a task lying on the critical path directly postpones the entire project. Non-critical tasks possess slack time, meaning their start can slip without delaying completion. Engineers use critical path analysis to identify bottlenecks and schedule workers. To compute earliest completion times, compute the longest path from the start node. To find slack times, compute latest permissible start dates via reverse topological traversal. Tasks whose earliest and latest start times coincide constitute the critical path.

Next step

Check your understanding

10 quick questions