Optimal Substructure and When It Fails
Rod cutting and matrix chains looked different, but their dynamic programs were built from the same two ingredients. This lesson names the first one, optimal substructure, and turns it into a checklist you can apply to a new problem. Then it does the more instructive thing: it shows a problem that looks just as innocent, the longest simple path in a graph, where optimal substructure fails, and explains exactly why. The second ingredient, overlapping subproblems, is the subject of the next lesson.
The definition
A problem has optimal substructure if an optimal solution to an instance contains within it optimal solutions to subproblems. "Contains" is the important word: we can only build the big answer from small answers if the small answers that appear inside an optimal big answer are themselves the best ones, otherwise looking them up in a table of best answers would give the wrong thing.
The argument that establishes it has the same four steps every time.
- A solution starts with a choice. Rod cutting: the length of the first piece. Matrix chain: where the last multiplication splits the chain.
- Suppose you were told the choice an optimal solution makes. Don't worry yet about how to find it; the DP will try every option.
- Identify the subproblems that remain after that choice, and describe the space of all subproblems that can arise this way. Rod cutting: a shorter rod. Matrix chain: a prefix and a suffix of the current subchain, so in general all subchains .
- Cut and paste. Show that the pieces of an optimal solution that solve the subproblems must be optimal for them. Assume one is not, replace it by a better solution of that subproblem, and show that the whole solution improves (and stays valid), a contradiction.
Step 4 has a hidden condition: the replacement must not interfere with the rest of the solution. In rod cutting, re-cutting the remainder of the rod cannot affect the first piece. In matrix chains, re-parenthesizing does not change the dimensions of its result, so the final multiplication still costs . This independence is what fails in the example below.
Choosing the subproblem space
Step 3 involves a design decision. The subproblem space should be as small as possible but closed: every subproblem that the recurrence generates must belong to it.
For rod cutting, the space "rods of length " is closed, because removing a first piece leaves a rod. For matrix chains, try the space "prefixes ": the split of at leaves the prefix , fine, but also the suffix , which is not a prefix. The space is not closed, so it must be enlarged to all subchains, of them instead of .
The running time of the resulting DP is roughly
| problem | subproblems | choices each | time |
|---|---|---|---|
| rod cutting | lengths | up to first pieces | |
| matrix chain | subchains | up to splits | |
| longest common subsequence | prefix pairs | at most 3 | |
| optimal BST | key ranges | up to roots |
The last two rows are the subjects of Longest Common Subsequence and Optimal Binary Search Trees.
Shortest paths have optimal substructure
Take an unweighted graph and a shortest path from to , measured in edges. If passes through a vertex , it splits into from to and from to . Claim: is a shortest path from to . Cut and paste: if some path from to were shorter, then followed by would be a walk from to shorter than . It might repeat vertices, but a walk can always be shortened to a simple path by cutting out the loops, which only makes it shorter still. Contradiction. So shortest paths are made of shortest paths, the fact behind Bellman-Ford, Dijkstra and Floyd-Warshall in the Graph Algorithms course.
Longest simple paths do not
Now ask for a longest simple path from to : the most edges on a path that never repeats a vertex. (Without "simple" the question makes no sense in a graph with a cycle, since you could loop forever.) Use this small undirected graph:
a ------ b
| \ |
| \ |
| \ |
d ------ c edges: a-b, b-c, c-d, d-a, a-cThe program lists every simple path between every pair and checks the substructure claim in both versions.
from itertools import permutations
edges = {("a", "b"), ("b", "c"), ("c", "d"), ("d", "a"), ("a", "c")}
adj = {v: set() for v in "abcd"}
for x, y in edges:
adj[x].add(y); adj[y].add(x)
def simple_paths(u, v):
out, stack = [], [[u]]
while stack:
path = stack.pop()
if path[-1] == v:
out.append(path)
continue
for w in sorted(adj[path[-1]]):
if w not in path:
stack.append(path + [w])
return out
def longest(u, v):
return max(simple_paths(u, v), key=len)
def shortest_len(u, v):
return min(len(p) for p in simple_paths(u, v)) - 1
P = ["a", "b", "c"]
print(f"longest a..c has length {len(longest('a', 'c')) - 1}; one of them is {'-'.join(P)}"
f" (a simple path: {P in simple_paths('a', 'c')})")
print("P passes through b; its piece a..b has length 1, but")
print("longest a..b:", "-".join(longest("a", "b")), " length", len(longest("a", "b")) - 1)
print("longest b..c:", "-".join(longest("b", "c")), " length", len(longest("b", "c")) - 1)
glued = longest("a", "b") + longest("b", "c")[1:]
print("gluing the two:", "-".join(glued), " simple:", len(set(glued)) == len(glued))
# the same check for shortest paths, over every pair and every middle vertex
ok = all(shortest_len(p[0], p[i]) == i
for u, v in permutations("abcd", 2)
for p in simple_paths(u, v) if len(p) - 1 == shortest_len(u, v)
for i in range(1, len(p)))
print("every prefix of every shortest path is a shortest path:", ok)longest a..c has length 2; one of them is a-b-c (a simple path: True)
P passes through b; its piece a..b has length 1, but
longest a..b: a-d-c-b length 3
longest b..c: b-a-d-c length 3
gluing the two: a-d-c-b-a-d-c simple: False
every prefix of every shortest path is a shortest path: True
A longest simple path from to is (or ), with 2 edges. Its piece from to has 1 edge, but the longest simple path from to is , with 3. So the longest path does not contain longest subpaths. Worse, trying to build the answer from longest pieces fails completely: the longest -to- and -to- paths glued together revisit and , so the result is not even a simple path.
What went wrong is the hidden condition from step 4. The two subproblems "longest simple path from to " and "longest simple path from to " are not independent: they compete for the same vertices. A vertex used by the first piece cannot be used by the second. The shortest-path version escapes because, as the proof showed, an optimal piece never wants to reuse vertices; in the longest version, each piece wants as many vertices as it can grab, and grabbing them hurts the other piece.
You might try to repair it by adding "the set of vertices still available" to the subproblem. That restores independence and gives a correct DP, but the subproblem space becomes all subsets of vertices, of them: the same idea as the Held-Karp algorithm for the travelling salesman problem, and still exponential. In fact the longest simple path problem is NP-hard (it contains the Hamiltonian path problem: is there a simple path with edges?), so nobody expects a polynomial DP for it. See the NP-completeness lessons in Selected Topics.
The repaired DP is easy to write for a small graph. Its state is a pair (set of vertices used, last vertex), with the set stored as a bitmask, and the program counts the states it fills.
def longest_simple_path(vertices, edges, u, v):
"""DP over (set of used vertices, last vertex): exponential, but correct"""
idx = {x: i for i, x in enumerate(vertices)}
adj = {x: set() for x in vertices}
for a, b in edges:
adj[a].add(b); adj[b].add(a)
reach = {(1 << idx[u], u)} # paths starting at u, described by (used set, end)
states, best = 0, -1
for size in range(1, len(vertices) + 1): # by number of vertices used: a valid order
layer = {(m, x) for m, x in reach if bin(m).count("1") == size}
states += len(layer)
for m, x in layer:
if x == v:
best = max(best, size - 1)
for y in adj[x]:
if not m >> idx[y] & 1:
reach.add((m | 1 << idx[y], y))
return best, states
edges = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "a"), ("a", "c")]
for u, v in [("a", "c"), ("a", "b"), ("b", "c")]:
length, states = longest_simple_path("abcd", edges, u, v)
print(f"longest simple path {u}..{v}: {length} edges ({states} reachable states)")
# a 4 x 4 grid graph: the state space grows like 2^|V| * |V|
grid = [f"{r}{c}" for r in range(4) for c in range(4)]
grid_edges = [(f"{r}{c}", f"{r}{c + 1}") for r in range(4) for c in range(3)] + \
[(f"{r}{c}", f"{r + 1}{c}") for r in range(3) for c in range(4)]
length, states = longest_simple_path(grid, grid_edges, "00", "33")
print(f"4 x 4 grid, corner to corner: {length} edges, {states} reachable states")longest simple path a..c: 2 edges (10 reachable states)
longest simple path a..b: 3 edges (10 reachable states)
longest simple path b..c: 3 edges (10 reachable states)
4 x 4 grid, corner to corner: 14 edges, 1677 reachable states
The small graph agrees with the enumeration above. On the 16-vertex grid the longest corner-to-corner path has 14 edges, visiting 15 of the 16 vertices (all 16 is impossible: colour the grid like a chessboard, and a path between two corners of the same colour has an odd number of vertices). The DP touched 1677 states here, but the state space is in general, over a million for 16 vertices, and it doubles with every added vertex.
Note: Longest paths are easy in a directed acyclic graph: there are no cycles to reuse, any path is automatically simple, and the subproblems "longest path ending at " are independent. The next lesson solves it, and it is the basis of critical-path scheduling.
Optimal substructure is not enough
Two warnings to carry into the rest of the course.
- Optimal substructure alone does not make a problem a DP problem. If the subproblems never repeat, divide and conquer is enough: merge sort has optimal substructure in a trivial sense, but its subproblems are disjoint, and a table would only waste memory.
- Optimal substructure is also what greedy algorithms need. A greedy algorithm makes one choice and solves a single subproblem, without comparing all choices. That is only correct when an extra property, the greedy-choice property, holds as well.
A quick sanity test for a proposed recurrence is to compare it with brute force on all small inputs, exactly as the programs in this course do. A recurrence that is wrong because substructure fails (like "longest path = longest piece + longest piece") usually breaks on an input with four or five elements.
Test yourself
In the cut-and-paste argument for optimal substructure, what must be true of the replacement solution for a subproblem?
- It must be the greedy choice
- It must combine with the rest of the solution without affecting its validity or cost
- It must be unique
- It must be found in polynomial time
Why are prefixes not a valid subproblem space for matrix-chain multiplication?
- There are too many of them
- Splitting a prefix produces a suffix piece , which is not a prefix
- Prefixes have no optimal substructure
- Prefixes cannot be parenthesized
Why does the longest simple path problem lack optimal substructure?
- Because longest paths are not unique
- Because the two pieces of a path share the pool of vertices, so making one piece longer can make the other impossible
- Because the graph is undirected
- Because the problem is in P
A DP has subproblems, each choosing among options with work per option. Its running time is...