DP on DAGs
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A DAG is a set of tasks or places joined by one-way arrows with no way to loop back. DP on a DAG processes the items in an order where everything an item depends on is finished first, so each item just picks the best answer among its incoming arrows.
Practical use cases
- Web app: Longest chain in a project plan. A project tool such as a Trello-like board lets tasks depend on other tasks. The manager clicks "show the critical path" to see which chain decides the finish date. Visiting tasks in dependency order and letting each task take the longest finish time among its prerequisites gives the answer in one pass, even with thousands of tasks.
- Web app: Counting ways through a course map. A college portal shows which courses unlock which. A student asks "in how many different orders can I reach the final project?". Each course adds up the counts of the courses that lead to it, so the page answers instantly instead of listing every path, which could be millions.
- System: Build systems and package managers. Tools like make, npm and Composer know which module needs which. They order the work so each piece is built after its parts, and the same order is used to compute the total build time or the slowest chain. Builds stay quick because each task is computed once, from answers that are already finished, never from scratch.
The story: The One-Way Scenic Railway
A toy-train in a hill resort ran on one-way tracks between stations S, A, B, C, D and T. Each track had a number: how many scenic points the ride earned. Kabir wanted the most scenic ride from S to T. He tried to follow every possible route with a pencil, but with more stations the routes multiplied like rabbits.
Mira noticed a lovely thing: no track ever returned to an earlier station. The map is a one-way graph with no loops, a DAG (directed acyclic graph). That means the stations can be lined up so that every track goes forward in the line. "Let us visit them in that order. When we reach a station, every station that leads into it has already been finished. Its best score is simply the best of (incoming station's score + track points)."
Station by station, the scores filled in: S 0, A 2, B 4, C 5, D 9, T 11. Following the "arrived from" notes backwards gave the route S → A → D → T. This is DP on a DAG: the table is attached to nodes, and the order of filling is the topological order. Many earlier problems (grid paths, stairs, LIS) were DAGs wearing disguise.
How to spot this problem, and where you need it
You have tasks or steps connected by one-way dependencies and want the longest, cheapest, or number of ways through them, but trying every path explodes in size.
Signs you need it
- The data is a set of "A must happen before B" rules, prerequisites, or one-way routes, and nothing can ever loop back.
- You want the longest, shortest, cheapest or most numerous way through, and a recursive search keeps re-doing the same sub-paths.
- The problem uses words like "dependency", "prerequisite", "critical path" or "number of distinct paths".
- Your page times out once the graph has a few hundred tasks because paths multiply.
Where to use it in a project
- A project or workflow tool that must show the critical path or earliest finish date.
- A course or onboarding flow where you count or rate the routes through unlocked steps.
- Build pipelines that need total time for the slowest chain of jobs.
The solution
First put the items in dependency order (a topological order) so every arrow points forward. Then walk through them once. For each item, look at all arrows coming in, take the best (or the sum) of the already finished answers plus the cost of that arrow, and store it. Since every item is computed exactly once and only from finished items, no path is ever re-explored.
Payoff: Before: trying every path, which can mean millions of routes. After: one pass over the tasks and arrows, so a 2,000-task plan is analysed instantly.
Explain it like I am 8
Stations in a line where trains only go forward. At each station you ask every arriving train, "How good was your journey so far?", then pick the best one and add the track's points. Because you work from the front of the line, you never need an answer you do not have yet.
How it works, step by step
- Order the stations so every track goes from earlier to later (a topological order; Kahn's method gives one).
best[S] = 0; other stations start as "not reached".- Go through stations in that order. For every outgoing track
u → vwith pointsw:best[v] = max(best[v], best[u] + w). - Remember which
ugave the best value if you need to print the route. - Read
best[T]. For the cheapest route, use min instead of max. Counting routes? Add instead.
The code in four languages
PHP
<?php
// Longest path from $start in a directed graph with no cycles (DAG).
function longestPath(array $edges, string $start): array {
$out = []; $indeg = [];
foreach ($edges as [$u, $v, $w]) {
$out[$u][] = [$v, $w];
$indeg[$u] = $indeg[$u] ?? 0;
$indeg[$v] = ($indeg[$v] ?? 0) + 1;
}
// Kahn's algorithm: line the stations up so every track goes forward
$queue = []; $order = [];
foreach ($indeg as $node => $d) if ($d === 0) $queue[] = $node;
while ($queue) {
$u = array_shift($queue);
$order[] = $u;
foreach ($out[$u] ?? [] as [$v, $w]) {
if (--$indeg[$v] === 0) $queue[] = $v;
}
}
$best = [$start => 0]; // only reached stations have a score
foreach ($order as $u) {
if (!isset($best[$u])) continue;
foreach ($out[$u] ?? [] as [$v, $w]) {
if (!isset($best[$v]) || $best[$u] + $w > $best[$v]) {
$best[$v] = $best[$u] + $w;
}
}
}
return $best;
}
$edges = [['S','A',2], ['S','B',4], ['A','C',3], ['B','C',1], ['A','D',7], ['C','T',5], ['D','T',2]];
$best = longestPath($edges, 'S');
echo $best['T'], "\n"; // 11JavaScript
// Longest path from start in a directed graph with no cycles (DAG).
function longestPath(edges, start) {
const out = {}, indeg = {};
for (const [u, v, w] of edges) {
(out[u] = out[u] || []).push([v, w]);
indeg[u] = indeg[u] || 0;
indeg[v] = (indeg[v] || 0) + 1;
}
// Kahn's algorithm: line the stations up so every track goes forward
const queue = [], order = [];
for (const node in indeg) if (indeg[node] === 0) queue.push(node);
while (queue.length) {
const u = queue.shift();
order.push(u);
for (const [v] of out[u] || []) {
if (--indeg[v] === 0) queue.push(v);
}
}
const best = { [start]: 0 }; // only reached stations have a score
for (const u of order) {
if (best[u] === undefined) continue;
for (const [v, w] of out[u] || []) {
if (best[v] === undefined || best[u] + w > best[v]) {
best[v] = best[u] + w;
}
}
}
return best;
}
const edges = [['S','A',2], ['S','B',4], ['A','C',3], ['B','C',1], ['A','D',7], ['C','T',5], ['D','T',2]];
console.log(longestPath(edges, 'S').T); // 11Java
import java.util.*;
public class Main {
record Track(String to, int weight) {}
// Longest path from start in a directed graph with no cycles (DAG).
static Map<String, Integer> longestPath(String[][] edges, String start) {
Map<String, List<Track>> out = new HashMap<>();
Map<String, Integer> indeg = new LinkedHashMap<>();
for (String[] e : edges) {
String u = e[0], v = e[1];
int w = Integer.parseInt(e[2]);
out.computeIfAbsent(u, k -> new ArrayList<>()).add(new Track(v, w));
indeg.putIfAbsent(u, 0);
indeg.merge(v, 1, Integer::sum);
}
// Kahn's algorithm: line the stations up so every track goes forward
Deque<String> queue = new ArrayDeque<>();
List<String> order = new ArrayList<>();
for (var entry : indeg.entrySet()) if (entry.getValue() == 0) queue.add(entry.getKey());
while (!queue.isEmpty()) {
String u = queue.poll();
order.add(u);
for (Track t : out.getOrDefault(u, List.of())) {
if (indeg.merge(t.to(), -1, Integer::sum) == 0) queue.add(t.to());
}
}
Map<String, Integer> best = new HashMap<>(); // only reached stations have a score
best.put(start, 0);
for (String u : order) {
if (!best.containsKey(u)) continue;
for (Track t : out.getOrDefault(u, List.of())) {
int candidate = best.get(u) + t.weight();
if (!best.containsKey(t.to()) || candidate > best.get(t.to())) {
best.put(t.to(), candidate);
}
}
}
return best;
}
public static void main(String[] args) {
String[][] edges = {{"S", "A", "2"}, {"S", "B", "4"}, {"A", "C", "3"}, {"B", "C", "1"},
{"A", "D", "7"}, {"C", "T", "5"}, {"D", "T", "2"}};
System.out.println(longestPath(edges, "S").get("T")); // 11
}
}Go
package main
import "fmt"
type edge struct {
from, to string
weight int
}
type track struct {
to string
weight int
}
// longestPath finds the longest path from start in a directed graph with no cycles (DAG).
func longestPath(edges []edge, start string) map[string]int {
out := map[string][]track{}
indeg := map[string]int{}
var nodes []string // every station, in first-seen order
seen := func(n string) {
if _, ok := indeg[n]; !ok {
indeg[n] = 0
nodes = append(nodes, n)
}
}
for _, e := range edges {
out[e.from] = append(out[e.from], track{e.to, e.weight})
seen(e.from)
seen(e.to)
indeg[e.to]++
}
// Kahn's algorithm: line the stations up so every track goes forward
var queue, order []string
for _, n := range nodes {
if indeg[n] == 0 {
queue = append(queue, n)
}
}
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
order = append(order, u)
for _, t := range out[u] {
indeg[t.to]--
if indeg[t.to] == 0 {
queue = append(queue, t.to)
}
}
}
best := map[string]int{start: 0} // only reached stations have a score
for _, u := range order {
if _, ok := best[u]; !ok {
continue
}
for _, t := range out[u] {
if old, ok := best[t.to]; !ok || best[u]+t.weight > old {
best[t.to] = best[u] + t.weight
}
}
}
return best
}
func main() {
edges := []edge{{"S", "A", 2}, {"S", "B", 4}, {"A", "C", 3}, {"B", "C", 1},
{"A", "D", 7}, {"C", "T", 5}, {"D", "T", 2}}
fmt.Println(longestPath(edges, "S")["T"]) // 11
}Time: O(V + E) · Extra space: O(V + E). Each station and each track is handled once: one pass for ordering, one for the scores.
Watch out for
- Using it on a graph with loops. The method needs a proper order, which only exists without cycles.
- Skipping the topological order and relaxing edges in random order, which uses scores that are not final yet.
- Starting every station at 0 for a longest path: unreached stations must stay "not reached", or they invent routes.
Quick check
- Why does a DAG make DP possible?
- It has few nodes
- Nodes can be ordered so every dependency comes first
- It has no weights
- What do we do at each station?
- Keep the best of (earlier score + track)
- Add all incoming scores
- Choose a random track
- Time complexity of DP on a DAG?
- O(V × E)
- O(V + E)
- O(2ⁿ)