Sub topic 3
Optimal Substructure
This chapter assumes you have read the earlier chapters on what makes an algorithm greedy and on the greedy choice property. It also assumes you can read Python and follow a proof by contradiction. The greedy choice property tells you that one particular first move is safe. Optimal substructure tells you what to do after that move: solve what is left the same way and trust that the pieces add up to an optimal whole.
The Definition
A problem has optimal substructure when every optimal solution to it is built from optimal solutions to smaller subproblems.
For greedy algorithms the statement gets more specific. Take a problem instance P. Make the greedy choice c. That leaves a smaller instance P' of the same kind of problem. Optimal substructure holds when the following is true:
- If S' is an optimal solution to P', then {c} ∪ S' is an optimal solution to P.
The two properties together give the whole correctness argument. The greedy choice property says some optimal solution contains c. Optimal substructure says the rest of that solution can be any optimal solution of P'. By induction on the size of the instance, repeating the greedy choice produces an optimal solution.
The Cut-and-Paste Proof Template
Most optimal substructure proofs use the same contradiction, often called cut-and-paste:
- Let S be an optimal solution to P that contains the greedy choice c. Write S = {c} ∪ T, where T solves the subproblem P'.
- Suppose T is not optimal for P'. Then some T* solves P' strictly better than T.
- Cut T out of S and paste T in. Check that {c} ∪ T is still a valid solution to P.
- Its value is strictly better than S, which contradicts the optimality of S.
Step 3 is where proofs go wrong. Pasting in T must not break any constraint that links c to the rest of the solution. If T could conflict with c, the argument fails, and the problem may not have the substructure you assumed.
Worked Example: Activity Selection
Activity selection is covered in full in a later chapter. Here we use it only to show the substructure. The input is a set of intervals [start, end), and the goal is the largest set of intervals that do not overlap. The greedy choice is the interval a₁ that finishes first.
The subproblem. After choosing a₁ = [s₁, f₁), only the intervals that start at or after f₁ are still compatible with it. Call that set P'. P' is another activity selection instance, and it is smaller.
The claim. If T is a maximum compatible set in P', then {a₁} ∪ T is a maximum compatible set in P.
The proof. The greedy choice property gives an optimal solution S that contains a₁. Every other interval in S is compatible with a₁. Because a₁ finishes first, every other interval in S starts at or after f₁, so T = S − {a₁} lies inside P'. Suppose T is not maximum in P', so some T in P' has |T| > |T|. Every interval in T starts at or after f₁, so none of them overlaps a₁. That makes {a₁} ∪ T valid, and it is larger than S, which is a contradiction. So OPT(P) = 1 + OPT(P').
The code below checks this identity against brute force on random small inputs. It also runs a recursive greedy that follows the substructure directly.
import random
from itertools import combinations
def compatible(subset):
s = sorted(subset, key=lambda iv: iv[1])
return all(s[i][1] <= s[i + 1][0] for i in range(len(s) - 1))
def brute_opt(intervals):
for k in range(len(intervals), 0, -1):
for combo in combinations(intervals, k):
if compatible(combo):
return k
return 0
def subproblem_after(first, intervals):
return [iv for iv in intervals if iv[0] >= first[1]]
def greedy_rec(intervals):
if not intervals:
return []
first = min(intervals, key=lambda iv: iv[1])
return [first] + greedy_rec(subproblem_after(first, intervals))
random.seed(1)
for trial in range(300):
intervals = []
for _ in range(random.randint(1, 8)):
s = random.randint(0, 15)
intervals.append((s, s + random.randint(1, 6)))
first = min(intervals, key=lambda iv: iv[1])
rest = subproblem_after(first, intervals)
assert brute_opt(intervals) == 1 + brute_opt(rest)
assert len(greedy_rec(intervals)) == brute_opt(intervals)
print("OPT(P) == 1 + OPT(P') held on all 300 random instances")Every interval has positive length, so first never lands in its own subproblem and the recursion always shrinks. If you allowed zero-length intervals such as (3, 3), the filter iv[0] >= first[1] would keep first and the recursion would never stop. This is a small case of the step-3 warning: you have to define the subproblem exactly.
Where Optimal Substructure Breaks
Shortest paths have optimal substructure. If the shortest route from u to w passes through v, then its u-to-v part is a shortest u-to-v route. Otherwise you could swap in a shorter one and get a shorter u-to-w route. This holds whenever the graph has no negative cycles.
Longest simple paths do not have this property. A simple path is one that never repeats a vertex. Take a square with vertices q, r, t, s and edges q–r, r–t, t–s, s–q.
graph = {"q": ["r", "s"], "r": ["q", "t"], "s": ["q", "t"], "t": ["r", "s"]}
def longest_simple_path(g, src, dst):
best = None
def dfs(node, path):
nonlocal best
if node == dst:
if best is None or len(path) > len(best):
best = list(path)
return
for nxt in g[node]:
if nxt not in path:
path.append(nxt)
dfs(nxt, path)
path.pop()
dfs(src, [src])
return best
print(longest_simple_path(graph, "q", "t")) # ['q', 'r', 't']
print(longest_simple_path(graph, "q", "r")) # ['q', 's', 't', 'r']
print(longest_simple_path(graph, "r", "t")) # ['r', 'q', 's', 't']A longest q-to-t path is q→r→t. Its q-to-r piece has one edge, but the longest q-to-r path has three. 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 is not a simple path. The cut-and-paste step fails because the two subproblems are not independent: vertices used in one part are not available to the other. Shortest paths never need to repeat a vertex, so their subproblems do not compete for vertices.
Optimal Substructure Is Necessary, Not Sufficient
Dynamic programming also depends on optimal substructure. The difference is how many subproblems each method considers:
| Approach | Subproblems examined per step | What it relies on |
|---|---|---|
| Dynamic programming | Every subproblem a choice could lead to | Optimal substructure and overlapping subproblems |
| Greedy | Only the one left after the greedy choice | Optimal substructure and the greedy choice property |
A problem can have optimal substructure and still defeat greedy. Coin change with denominations {1, 3, 4} is one example. An optimal way to make amount n is one coin plus an optimal way to make the smaller remainder, so the substructure is there. But the greedy choice of the largest coin is not always part of some optimal solution. The next chapter looks at this failure in detail. Here the point is that proving optimal substructure covers only half of a greedy correctness proof.
Common Errors
- Changing the problem type. The subproblem must be an instance of the same problem, so the same algorithm applies to it. If the leftover piece carries an extra constraint, such as "must also avoid time 7", either write that constraint into the problem definition or admit that the recursion does not apply.
- Defining the remainder carelessly. In activity selection, "intervals other than a₁" is the wrong subproblem. The right one is "intervals compatible with a₁". With the wrong definition, the pasted solution can overlap the choice.
- Proving substructure for one optimal solution only. The claim must hold for any optimal S' of the subproblem. The algorithm finds some optimal S', not one you picked in advance.
- Treating substructure as proof that greedy works. Without the greedy choice property, you have only shown that some recursive method could work. That method might be dynamic programming.
Exercises
Exercise
In fractional knapsack, the greedy choice takes as much as possible of the item with the highest value per weight. Suppose that item fits completely, with weight w and value v, and the capacity is W. State the subproblem P', and give the cut-and-paste argument that v + OPT(P') = OPT(P), assuming some optimal solution takes all of that item.
Show answer
P' is the same item set without that item, with capacity W − w. Let S be an optimal solution that takes all of the item, and let T be the rest of S. T uses at most W − w capacity and contains only the other items, so it is a feasible solution of P'. If some T had value greater than T in P', then the item plus T would also fit in capacity W and be worth more than S. That contradicts the optimality of S. So T is optimal for P', and OPT(P) = v + OPT(P').
Exercise
Does "find a path from u to w with the fewest edges in an unweighted graph" have optimal substructure? Justify your answer with the independence condition.
Show answer
Yes. If a fewest-edge path from u to w goes through v, then its u-to-v and v-to-w parts must also have the fewest edges. A shorter replacement for either part would give a shorter whole path. If the joined path repeats a vertex, cutting out the cycle makes it shorter still. A fewest-edge path never needs to revisit a vertex, so the two parts do not compete for vertices and are independent.
Exercise
The subproblem in greedy_rec is defined by iv[0] >= first[1]. If you change it to iv[0] > first[1], does OPT(P) = 1 + OPT(P') still hold for half-open intervals [start, end)? Give a small input that shows the answer.
Show answer
No. Intervals that start exactly at f₁ are compatible with a₁ but would be dropped from P'. For [(0, 2), (2, 4)], OPT(P) = 2. With the strict filter, P' is empty, so 1 + OPT(P') = 1. The subproblem no longer contains every compatible interval, and the cut-and-paste argument fails.