Overlapping Subproblems and the Subproblem Graph
Optimal substructure says that a big optimal answer is made of small optimal answers. That alone suggests recursion, and for many problems plain recursion is the right algorithm: merge sort and quicksort split their input into pieces that never meet again. Dynamic programming pays off only when a recursive solution keeps running into the same subproblems, which is the second ingredient, overlapping subproblems. This lesson measures the overlap, makes the subproblem graph precise, and uses it to solve a problem that the previous lesson left open: the longest path in a directed acyclic graph.
Measuring the overlap
A recursive algorithm has overlapping subproblems when the total number of calls is much larger than the number of distinct calls. The program below counts both for three recursions: merge sort on 64 elements, the Fibonacci recurrence, and the rod-cutting recurrence.
from collections import Counter
def count_calls(f, *args):
seen = Counter()
def wrapped(*a):
seen[a] += 1
return f(wrapped, *a)
wrapped(*args)
return sum(seen.values()), len(seen)
def merge_sort_calls(rec, lo, hi): # subproblem = index range [lo, hi)
if hi - lo > 1:
mid = (lo + hi) // 2
rec(lo, mid); rec(mid, hi)
def fib(rec, n):
return n if n < 2 else rec(n - 1) + rec(n - 2)
def rod(rec, n):
return 0 if n == 0 else max(rec(n - i) for i in range(1, n + 1))
for name, f, arg in [("merge sort, n = 64", merge_sort_calls, (0, 64)),
("fibonacci(20)", fib, (20,)),
("rod cutting, n = 16", rod, (16,))]:
total, distinct = count_calls(f, *arg)
print(f"{name:20}: {total:6} calls, {distinct:4} distinct subproblems, ratio {total / distinct:7.1f}")merge sort, n = 64 : 127 calls, 127 distinct subproblems, ratio 1.0
fibonacci(20) : 21891 calls, 21 distinct subproblems, ratio 1042.4
rod cutting, n = 16 : 65536 calls, 17 distinct subproblems, ratio 3855.1
Merge sort never solves the same range twice: the ratio is exactly 1, and a memo table would only cost memory. The Fibonacci recursion solves 21 distinct subproblems with 21,891 calls, and rod cutting 17 subproblems with 65,536. A large ratio is the signature of overlapping subproblems; memoization or a bottom-up table reduces it to 1.
Note: The Fibonacci recursion is the DSA course's first DP example, in Memoization. The number of calls it makes, , is itself a Fibonacci-type number, so it grows like with .
The subproblem graph, precisely
For a recurrence, define the subproblem graph :
- one vertex for each distinct subproblem that can arise from the original question;
- a directed edge whenever the recurrence for refers directly to .
Three facts follow, and each is worth knowing by heart.
- must be acyclic, or the recurrence is circular. Its sinks (vertices without outgoing edges) are the base cases.
- A bottom-up order is a reverse topological order of : every vertex after everything it points to. Memoized recursion is a depth-first search of that finishes each vertex after its successors, which produces such an order automatically.
- The running time is times the work per edge, if each subproblem is solved once and each edge is looked at once, where and are the vertex and edge counts of .
For rod cutting and . For matrix chains, vertex has outgoing edges (two subchains per split), so . The recursion tree of the naive algorithm is unfolded into a tree, and its size is the number of paths from the root of , which is exponential in both cases.
Longest paths in a DAG
The previous lesson showed that longest simple paths have no optimal substructure in general graphs. In a directed acyclic graph every path is simple automatically, so the problem becomes easy. Here is a classic application. A renovation consists of tasks with durations (in days) and prerequisites; tasks with no dependency between them can run in parallel. The shortest possible project length is the length of the longest path through the dependency graph, the critical path, where a path's length is the sum of the durations of its tasks.
task days needs
survey 2 -
demolish 3 survey
order 4 survey
plumbing 5 demolish
wiring 4 demolish, order
walls 3 plumbing, wiring
floor 2 demolish
paint 2 walls
fit-out 3 walls, floor, order
handover 1 paint, fit-outLet be the earliest day by which task can be finished. It must wait for its slowest prerequisite:
The subproblem graph of this recurrence is the dependency graph itself (with the edges reversed), so it is acyclic and the recurrence is valid. Evaluate it in topological order, prerequisites first, and remember which prerequisite was the slowest so the critical path can be reconstructed.
tasks = { # name: (days, prerequisites)
"survey": (2, []), "demolish": (3, ["survey"]), "order": (4, ["survey"]),
"plumbing": (5, ["demolish"]), "wiring": (4, ["demolish", "order"]),
"walls": (3, ["plumbing", "wiring"]), "floor": (2, ["demolish"]),
"paint": (2, ["walls"]), "fit-out": (3, ["walls", "floor", "order"]),
"handover": (1, ["paint", "fit-out"]),
}
def topological_order(tasks):
order, state = [], {}
def visit(v): # depth-first: finish v after its prerequisites
if state.get(v) == "done":
return
assert state.get(v) != "active", "cycle!"
state[v] = "active"
for u in tasks[v][1]:
visit(u)
state[v] = "done"
order.append(v)
for v in tasks:
visit(v)
return order
finish, via = {}, {}
for v in topological_order(tasks):
days, needs = tasks[v]
start = max((finish[u] for u in needs), default=0)
via[v] = max(needs, key=lambda u: finish[u]) if needs else None
finish[v] = start + days
print(f"{v:9} starts day {start:2}, finishes day {finish[v]:2}" + (f" (waits for {via[v]})" if needs else ""))
path, v = [], max(finish, key=finish.get)
while v is not None:
path.append(v)
v = via[v]
print("project length:", max(finish.values()), "days; critical path:", " -> ".join(reversed(path)))survey starts day 0, finishes day 2
demolish starts day 2, finishes day 5 (waits for survey)
order starts day 2, finishes day 6 (waits for survey)
plumbing starts day 5, finishes day 10 (waits for demolish)
wiring starts day 6, finishes day 10 (waits for order)
walls starts day 10, finishes day 13 (waits for plumbing)
floor starts day 5, finishes day 7 (waits for demolish)
paint starts day 13, finishes day 15 (waits for walls)
fit-out starts day 13, finishes day 16 (waits for walls)
handover starts day 16, finishes day 17 (waits for fit-out)
project length: 17 days; critical path: survey -> demolish -> plumbing -> walls -> fit-out -> handover
The project takes 17 days, and the tasks on the critical path survey, demolish, plumbing, walls, fit-out, handover cannot slip without delaying everything. There is a tie hidden in the trace: walls waits for plumbing and wiring, which both finish on day 10, so survey, order, wiring, walls, fit-out, handover is a second critical path, and the program reports the first one it found. Tasks off every critical path have slack: floor is finished on day 7 but fit-out cannot start before day 13, so floor could start up to 6 days late. Each task and each dependency is handled once: , the bound of fact 3. The same algorithm with weights on edges instead of vertices gives shortest or longest paths in any DAG, a topic of Graph Algorithms.
In C++
The same computation with tasks numbered in a topological order already (the order of the table above is one), so a single forward loop suffices.
#include <cstdio>
#include <string>
#include <vector>
int main() {
std::vector<std::string> name = {"survey", "demolish", "order", "plumbing", "wiring",
"walls", "floor", "paint", "fit-out", "handover"};
std::vector<int> days = {2, 3, 4, 5, 4, 3, 2, 2, 3, 1};
std::vector<std::vector<int>> needs = {{}, {0}, {0}, {1}, {1, 2}, {3, 4}, {1}, {5}, {5, 6, 2}, {7, 8}};
int n = static_cast<int>(name.size());
std::vector<int> finish(n), via(n, -1);
for (int v = 0; v < n; ++v) { // prerequisites always have smaller numbers
int start = 0;
for (int u : needs[v])
if (finish[u] > start) { start = finish[u]; via[v] = u; }
finish[v] = start + days[v];
}
int last = 0;
for (int v = 1; v < n; ++v) if (finish[v] > finish[last]) last = v;
std::printf("project length: %d days\ncritical path (backwards):", finish[last]);
for (int v = last; v != -1; v = via[v]) std::printf(" %s", name[v].c_str());
std::printf("\n");
}project length: 17 days
critical path (backwards): handover fit-out walls plumbing demolish survey
When memoization does not help
The flip side of overlapping subproblems: if the subproblem graph is a tree, there is nothing to share. The program below memoizes a merge-sort-style recursion and a Fibonacci recursion and reports cache hits.
from functools import cache
@cache
def split_sum(lo, hi): # sum of lo..hi-1 by halving: disjoint subproblems
if hi - lo == 1:
return lo
mid = (lo + hi) // 2
return split_sum(lo, mid) + split_sum(mid, hi)
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print("split_sum(0, 1024) =", split_sum(0, 1024), split_sum.cache_info())
print("fib(90) =", fib(90), fib.cache_info())split_sum(0, 1024) = 523776 CacheInfo(hits=0, misses=2047, maxsize=None, currsize=2047)
fib(90) = 2880067194370816120 CacheInfo(hits=88, misses=91, maxsize=None, currsize=91)
The halving recursion stores 2047 results and never reads one back (0 hits): pure overhead. The Fibonacci recursion stores 91 and reuses 88, turning an impossible computation ( calls) into 179.
Test yourself
Which recursion has overlapping subproblems?
- Merge sort
- Binary search
- The rod-cutting recurrence
- Quicksort
What is a valid bottom-up evaluation order for a DP?
- Any topological order of the subproblem graph, where edges point from a subproblem to the ones it needs
- A reverse topological order of that graph
- Breadth-first order from the original problem
- Alphabetical order of the subproblems
Why can longest paths be found by DP in a directed acyclic graph but not in a general graph?
- Because a DAG has fewer edges
- Because in a DAG every path is simple, so the subproblems 'longest path ending at ' are independent
- Because DAGs have no weights
- Because topological sort is faster than DFS