Sub topic 3
Optimal substructure: building answers from sub-answers
The previous chapter showed that naive recursion often solves the same subproblem many times. That repetition is the reason caching pays off. Caching only gives correct answers, though, when the best answer to a problem can be assembled from the best answers to its subproblems. That second property is called optimal substructure. This chapter explains what it means, how to argue that a problem has it, and how to recognize problems that lack it.
This chapter assumes you can write recursive Python functions with base cases, read Big-O notation, and work with lists and dictionaries.
What optimal substructure means
A problem has optimal substructure when an optimal solution to it contains optimal solutions to smaller instances of the same problem. If you know the best answers to the subproblems, you can combine them with a simple rule, usually min, max, or +, and get the best answer to the whole problem.
Fibonacci isn't an optimization problem, but it has the same shape: fib(n) is built exactly from fib(n - 1) and fib(n - 2). For optimization problems the claim is stronger. It says you never need a second-best sub-answer to build the best overall answer.
The two properties play different roles:
| Property | Question it answers | What it gives you |
|---|---|---|
| Overlapping subproblems | Do the same subproblems come up again and again? | Caching saves time |
| Optimal substructure | Can the best answer be built from the best sub-answers? | A correct recurrence exists |
Dynamic programming needs both. Merge sort has optimal substructure in a loose sense, since a sorted list is built from sorted halves, but its subproblems never overlap. Plain divide and conquer is enough there. A problem whose subproblems overlap but whose optimum can't be assembled from sub-optima can't be solved by a cached recurrence at all.
A worked example: making change
Take the minimum coin problem: given coin denominations and a target amount, find the fewest coins that add up to the amount. Each coin can be used any number of times.
Suppose the coins are [1, 3, 4] and the amount is 6. Some coin has to be the last one added. If that coin is c, the remaining coins make 6 - c, and they must make it with as few coins as possible. Otherwise you could swap in a better way of making 6 - c and get a better total. So:
- If the last coin is 1, the best total is 1 + (fewest coins for 5).
- If the last coin is 3, the best total is 1 + (fewest coins for 3).
- If the last coin is 4, the best total is 1 + (fewest coins for 2).
The answer is the minimum of the three. That is optimal substructure. The next chapter turns this into a formal state and recurrence. Here is the idea written as plain recursion, without caching, which is fine for small amounts:
def min_coins(coins, amount):
if amount == 0:
return 0
best = float('inf')
for c in coins:
if c <= amount:
sub = min_coins(coins, amount - c)
if sub + 1 < best:
best = sub + 1
return best
print(min_coins([1, 3, 4], 6)) # 2 (3 + 3)If no combination works, the function returns float('inf'), because inf + 1 is still inf. Later chapters convert that to -1.
Checking the claim by brute force
When you aren't sure a problem has optimal substructure, compare your recurrence against an exhaustive search on small inputs. This brute-force version tries every multiset of coins in order of size:
from itertools import combinations_with_replacement
def brute_force_min_coins(coins, amount):
for k in range(0, amount + 1):
for combo in combinations_with_replacement(coins, k):
if sum(combo) == amount:
return k
return float('inf')
def min_coins(coins, amount):
if amount == 0:
return 0
best = float('inf')
for c in coins:
if c <= amount:
best = min(best, min_coins(coins, amount - c) + 1)
return best
for coins in ([1, 3, 4], [2, 5], [1, 5, 10, 25], [3, 7]):
for amount in range(0, 20):
assert min_coins(coins, amount) == brute_force_min_coins(coins, amount), (coins, amount)
print("recurrence matches brute force")Agreement on small cases doesn't prove anything, but disagreement immediately shows a broken assumption. This check costs little and catches most mistakes in a recurrence.
Proving it: the cut-and-paste argument
The standard proof that a problem has optimal substructure is the cut-and-paste argument. It is a proof by contradiction with three steps:
- Assume you have an optimal solution, and identify the subproblem solution it contains.
- Suppose that sub-solution is not optimal for its subproblem. Then a strictly better one exists.
- Cut out the old sub-solution and paste in the better one. If the result is still a valid solution to the whole problem and is strictly better, you have contradicted the assumption that the original was optimal.
For coin change, the pasted-in collection still sums to the target, so step 3 works. For shortest paths in a graph with non-negative edge weights, it works too. If the shortest path from u to w passes through v, its u-to-v portion must itself be a shortest path. If a shorter one existed, splicing it in would shorten the whole path.
The phrase "still a valid solution" in step 3 is where the argument can fail. The pasted piece has to fit without breaking any rule of the whole problem.
When optimal substructure fails
The classic counterexample is the longest simple path, the longest path between two vertices that never repeats a vertex. Take a four-node cycle q - r - t - s - q:
graph = {
'q': ['r', 's'],
'r': ['q', 't'],
's': ['q', 't'],
't': ['r', 's'],
}
def simple_paths(g, start, end, path=None):
if path is None:
path = [start]
if start == end:
yield list(path)
return
for nxt in g[start]:
if nxt not in path:
path.append(nxt)
yield from simple_paths(g, nxt, end, path)
path.pop()
def longest(g, a, b):
return max(simple_paths(g, a, b), key=len)
print(longest(graph, 'q', 't')) # ['q', 'r', 't']
print(longest(graph, 'q', 'r')) # ['q', 's', 't', 'r']
print(longest(graph, 'r', 't')) # ['r', 'q', 's', 't']The longest simple path from q to t goes through r, but its q-to-r piece is a single edge, not the longest q-to-r path. Joining the longest q-to-r path with the longest r-to-t path gives q, s, t, r, q, s, t, which repeats vertices and isn't simple.
The cause is that the subproblems are not independent. The vertices used by one piece limit what the other piece may use. A cached recurrence assumes the best answer for "q to r" is the same no matter where it will be used. Here it isn't.
Fixing a failure by enlarging the state
Sometimes a problem seems to lack optimal substructure only because the subproblem is described too narrowly. The fix is to add information to the subproblem until the pieces become independent.
Suppose each coin type may be used at most once. Then "fewest coins for amount a" no longer has optimal substructure. The best way to make a - c might already use coin c. If the subproblem becomes "fewest coins for amount a using only the first i coin types", each coin's decision is made in exactly one place and the pieces no longer conflict. This is the same move that makes 0/1 knapsack work later in the tutorial.
Enlarging the state doesn't always help. For the longest simple path, the extra information you need is the set of vertices already visited. That gives exponentially many states, so the "DP" is no faster than brute force. The problem is NP-hard, so no small fix is expected.
Optimal substructure is not the greedy-choice property
Greedy algorithms also depend on optimal substructure, and they need one more property: that a locally best choice made now is always part of some optimal solution. Dynamic programming makes no such bet. It tries every choice at each step and keeps the best.
The coin set [1, 3, 4] shows the difference:
def greedy_coins(coins, amount):
count = 0
for c in sorted(coins, reverse=True):
count += amount // c
amount %= c
return count if amount == 0 else -1
def min_coins(coins, amount):
if amount == 0:
return 0
best = float('inf')
for c in coins:
if c <= amount:
best = min(best, min_coins(coins, amount - c) + 1)
return best
print(greedy_coins([1, 3, 4], 6)) # 3 (4 + 1 + 1)
print(min_coins([1, 3, 4], 6)) # 2 (3 + 3)Greedy takes the 4 first and is then stuck with two 1s. The problem still has optimal substructure. What fails is the greedy-choice property. For coin sets like US coins [1, 5, 10, 25], greedy happens to be optimal, and that is why it can seem correct in general.
Beyond min and max
The same structure covers problems that count or decide rather than optimize. "How many ways can I make amount a?" combines sub-answers with +. "Can I make amount a at all?" combines them with or. In each case the answer to a problem is a fixed function of the answers to its subproblems. For counting there is an extra condition: the subproblems must split the solutions into groups that don't overlap, or some solutions get counted twice.
Common mistakes
- Assuming the property without checking it. Run the cut-and-paste argument, or compare against brute force on small inputs.
- Defining a subproblem that loses a constraint. Limited supply, "no two adjacent", and "already used" rules usually need an extra state dimension.
- Confusing DP with greedy. If your recurrence commits to one choice instead of comparing all of them, you have written a greedy algorithm and need a separate proof that it is correct.
- Double counting in counting problems. Counting ordered sequences when the problem asks for unordered combinations is the usual case.
Exercise
The cheapest-flight problem asks for the lowest-cost route from city A to city B, with non-negative ticket prices. A variant adds the rule "use at most k flights." Does the original have optimal substructure with the subproblem "cheapest cost from A to city X"? Does the variant, with the same subproblem?
Show answer
The original does. By cut-and-paste, the A-to-X part of a cheapest A-to-B route must be a cheapest A-to-X route, or swapping in a cheaper one would lower the total. The variant does not with that subproblem, because the cheapest A-to-X route might use too many flights to leave room for the rest of the trip. Adding the flight count to the state, "cheapest cost from A to X using at most j flights", restores optimal substructure.
Exercise
For coins [1, 5, 6, 9] and amount 11, what does largest-coin-first greedy return, what does the optimal recurrence return, and which property explains the difference?
Show answer
Greedy takes 9, then 1 and 1, for 3 coins. The optimal answer is 5 + 6, which is 2 coins. The problem has optimal substructure, so the recurrence that tries every last coin finds 2. Greedy fails because the greedy-choice property doesn't hold for this coin set: taking the largest coin first isn't always part of an optimal solution.
Exercise
Explain in one or two sentences why the longest simple path problem lacks optimal substructure, using the idea of independent subproblems.
Show answer
Joining two sub-paths into one simple path requires that they share no vertices except the meeting point. The best answer to one subproblem therefore depends on which vertices the other uses. Because the subproblems aren't independent, their individual optima can combine into an invalid path.