TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Optimal Substructure and When It Fails

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.

  1. A solution starts with a choice. Rod cutting: the length of the first piece. Matrix chain: where the last multiplication splits the chain.
  2. 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.
  3. 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 Ai..jA_{i..j}.
  4. 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 Ai..kA_{i..k} does not change the dimensions of its result, so the final multiplication still costs pi−1pkpjp_{i-1} p_k p_j. 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 0..n0..n" is closed, because removing a first piece leaves a rod. For matrix chains, try the space "prefixes A1..jA_{1..j}": the split of A1..jA_{1..j} at kk leaves the prefix A1..kA_{1..k}, fine, but also the suffix Ak+1..jA_{k+1..j}, which is not a prefix. The space is not closed, so it must be enlarged to all subchains, Θ(n2)\Theta(n^2) of them instead of nn.

The running time of the resulting DP is roughly

(number of subproblems)×(number of choices per subproblem)×(work per choice).\text{(number of subproblems)} \times \text{(number of choices per subproblem)} \times \text{(work per choice)}.
problem subproblems choices each time
rod cutting n+1n + 1 lengths up to nn first pieces Θ(n2)\Theta(n^2)
matrix chain Θ(n2)\Theta(n^2) subchains up to n−1n - 1 splits Θ(n3)\Theta(n^3)
longest common subsequence Θ(mn)\Theta(mn) prefix pairs at most 3 Θ(mn)\Theta(mn)
optimal BST Θ(n2)\Theta(n^2) key ranges up to nn roots Θ(n3)\Theta(n^3)

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 PP from uu to vv, measured in edges. If PP passes through a vertex ww, it splits into P1P_1 from uu to ww and P2P_2 from ww to vv. Claim: P1P_1 is a shortest path from uu to ww. Cut and paste: if some path P1′P_1' from uu to ww were shorter, then P1′P_1' followed by P2P_2 would be a walk from uu to vv shorter than PP. 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 uu to vv: 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:

text
    a ------ b
    | \      |
    |   \    |
    |     \  |
    d ------ c          edges: a-b, b-c, c-d, d-a, a-c

The program lists every simple path between every pair and checks the substructure claim in both versions.

python · try it yourself
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 aa to cc is a−b−ca - b - c (or a−d−ca - d - c), with 2 edges. Its piece from aa to bb has 1 edge, but the longest simple path from aa to bb is a−d−c−ba - d - c - b, with 3. So the longest path does not contain longest subpaths. Worse, trying to build the answer from longest pieces fails completely: the longest aa-to-bb and bb-to-cc paths glued together revisit cc and dd, 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 aa to bb" and "longest simple path from bb to cc" 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, 2∣V∣2^{|V|} 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 ∣V∣−1|V| - 1 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.

python · try it yourself
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 2∣V∣⋅∣V∣2^{\lvert V \rvert} \cdot \lvert V \rvert 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 vv" 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?

  1. It must be the greedy choice
  2. It must combine with the rest of the solution without affecting its validity or cost
  3. It must be unique
  4. It must be found in polynomial time

Why are prefixes A1..jA_{1..j} not a valid subproblem space for matrix-chain multiplication?

  1. There are too many of them
  2. Splitting a prefix produces a suffix piece Ak+1..jA_{k+1..j}, which is not a prefix
  3. Prefixes have no optimal substructure
  4. Prefixes cannot be parenthesized

Why does the longest simple path problem lack optimal substructure?

  1. Because longest paths are not unique
  2. Because the two pieces of a path share the pool of vertices, so making one piece longer can make the other impossible
  3. Because the graph is undirected
  4. Because the problem is in P

A DP has Θ(n2)\Theta(n^2) subproblems, each choosing among O(n)O(n) options with O(1)O(1) work per option. Its running time is...

  1. O(n2)O(n^2)
  2. O(n3)O(n^3)
  3. O(2n)O(2^n)
  4. O(nlg⁡n)O(n \lg n)