Longest path in a Directed Acyclic Graph

Pattern: Topological sort

medium

Longest paths are hard in general graphs but easy in a DAG: process vertices in topological order and relax each edge u → v with dist[v] = max(dist[v], dist[u] + w), starting from dist[source] = 0. Unreached vertices stay unreached.

The problem

Given a weighted DAG and a source s, return the length of the longest path from s to every vertex, or -1 where a vertex cannot be reached. Vertices are numbered from 0 and each edge is [u, v, weight]. GFG prints INF for unreachable vertices; this guide uses -1.

Think first

  • Why is this hard in a graph with cycles?
  • What does a DAG give you?
  • Which vertices start as reachable?

Hints

    Brute force, and why it fails

    Try every path from the source: exponential.

    The key insight

    In topological order, the longest way into each vertex is known before its outgoing edges are used.

    Dry run

    dist- 0 2 6 - -

    Source 1. dist[1] = 0. Edges from 1: to 3 (6) and to 2 (2).

    Step 1 of 3

    The plan

    dist = none except dist[s] = 0
    for u in topological order: if dist[u] known: for (v, w): dist[v] = max(dist[v], dist[u] + w)
    

    Complexity

    Time
    O(V + E)
    Space
    O(V + E)

    One topological pass.

    Edge cases

    • Vertices before the source: -1.
    • Negative weights: allowed in a DAG.
    • A single vertex.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> longestPath(int n, int[][] edges, int s) {
            List<List<int[]>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            int[] indegree = new int[n];
            for (int[] e : edges) { adj.get(e[0]).add(new int[]{e[1], e[2]}); indegree[e[1]]++; }
            Queue<Integer> q = new ArrayDeque<>();
            for (int i = 0; i < n; i++) if (indegree[i] == 0) q.add(i);
            long[] dist = new long[n];
            Arrays.fill(dist, Long.MIN_VALUE);      // not reached yet
            dist[s] = 0;
            while (!q.isEmpty()) {                  // topological order: every way into a vertex is known before leaving it
                int u = q.poll();
                for (int[] e : adj.get(u)) {
                    if (dist[u] != Long.MIN_VALUE) dist[e[0]] = Math.max(dist[e[0]], dist[u] + e[1]);
                    if (--indegree[e[0]] == 0) q.add(e[0]);
                }
            }
            List<Integer> out = new ArrayList<>();
            for (long d : dist) out.add(d == Long.MIN_VALUE ? -1 : (int) d);
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> longestPath(int n, vector<vector<int>>& edges, int s) {
            vector<vector<pair<int, int>>> adj(n);
            vector<int> indegree(n, 0);
            for (const vector<int>& e : edges) { adj[e[0]].push_back(make_pair(e[1], e[2])); indegree[e[1]]++; }
            queue<int> q;
            for (int i = 0; i < n; i++) if (indegree[i] == 0) q.push(i);
            vector<long long> dist(n, LLONG_MIN);   // not reached yet
            dist[s] = 0;
            while (!q.empty()) {                    // topological order: every way into a vertex is known before leaving it
                int u = q.front();
                q.pop();
                for (const pair<int, int>& e : adj[u]) {
                    if (dist[u] != LLONG_MIN) dist[e.first] = max(dist[e.first], dist[u] + e.second);
                    if (--indegree[e.first] == 0) q.push(e.first);
                }
            }
            vector<int> out;
            for (long long d : dist) out.push_back(d == LLONG_MIN ? -1 : static_cast<int>(d));
            return out;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def longestPath(self, n: int, edges: list[list[int]], s: int) -> list[int]:
            adj, indegree = [[] for _ in range(n)], [0] * n
            for u, v, w in edges:
                adj[u].append((v, w))
                indegree[v] += 1
            q = deque(i for i in range(n) if indegree[i] == 0)
            dist = [None] * n                       # None: not reached yet
            dist[s] = 0
            while q:                                # topological order: every way into a vertex is known first
                u = q.popleft()
                for v, w in adj[u]:
                    if dist[u] is not None and (dist[v] is None or dist[u] + w > dist[v]):
                        dist[v] = dist[u] + w
                    indegree[v] -= 1
                    if indegree[v] == 0:
                        q.append(v)
            return [-1 if d is None else d for d in dist]

    Common mistakes

    • Relaxing from unreached vertices.
    • Using Dijkstra with negated weights, which fails.

    Similar problems