Shortest Path in DAG

medium

Given a weighted directed acyclic graph (DAG) with V vertices (0 .. V-1) and edges edges[i] = [u, v, w] (a directed edge u → v of weight w), return an array dist where dist[i] is the shortest distance from source vertex 0 to vertex i, or -1 if i is unreachable.

Hints

On a DAG you don't need Dijkstra — use a topological order.
Process vertices in topological order and relax each one's outgoing edges.
Every vertex's shortest distance is final by the time you reach it.

Common doubts

In topo order, all paths into a vertex come from earlier-processed vertices, so its distance is already minimal when you relax its edges.
Yes — a DAG has no cycles, hence no negative cycles, so relaxation in topo order stays correct.
When the graph isn't a DAG but has no negative cycle; then no topological order exists.

Interview follow-ups

Store a predecessor for each vertex whenever you relax an improving edge.
Same topo relaxation with max instead of min — longest path is NP-hard on general graphs but linear on a DAG.

Fun facts

  • DAG shortest path is one of the few shortest-path problems that's linear-time.
  • The same topological relaxation solves DAG longest path, used in critical-path scheduling.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
Example 1
Input: V = 4, edges = [[0,1,2],[0,2,4],[1,2,1],[2,3,3]]
Output: [0, 2, 3, 6]
0→1→2→3 gives distances 0,2,3,6 (the 0→2 direct edge of 4 is beaten by 0→1→2 = 3).
Example 2
Input: V = 4, edges = [[0,1,1],[2,3,1]]
Output: [0, 1, -1, -1]
Vertices 2 and 3 are unreachable from 0.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - the graph is a DAG - edges are [u, v, w] directed

Solve this problem →