Sub topic 8
Dynamic programming: optimal substructure and overlapping subproblems
This chapter assumes you know Big-O notation, can write and trace recursive functions, and can solve simple recurrences such as T(n) = T(n-1) + 1. The later chapters on knapsack, LCS, matrix chain and coin change all reuse the ideas introduced here.
What dynamic programming is
Dynamic programming (DP) solves a problem by splitting it into smaller subproblems, solving each distinct subproblem once, and storing the answer for reuse. It applies when two properties hold.
- Optimal substructure. An optimal solution to the problem contains optimal solutions to its subproblems.
- Overlapping subproblems. The recursion meets the same subproblem many times.
Divide and conquer (merge sort, for example) has the first property but not the second, because its subproblems are disjoint. Caching would gain nothing there. Greedy algorithms also need optimal substructure, but they commit to one choice without comparing alternatives. DP tries every choice for the first step and keeps the best.
Overlapping subproblems: Fibonacci
The Fibonacci recurrence F(n) = F(n-1) + F(n-2) shows the overlap clearly. The diagram below is the call tree for fib(4).
Without caching, the number of calls satisfies T(n) = T(n-1) + T(n-2) + 1, which grows as Θ(φⁿ) with φ ≈ 1.618. Only n + 1 distinct subproblems exist, so most of that work is repeated.
def fib_naive(n, counter):
counter[0] += 1
if n < 2:
return n
return fib_naive(n - 1, counter) + fib_naive(n - 2, counter)
def fib_memo(n, memo, counter):
counter[0] += 1
if n < 2:
return n
if n in memo:
return memo[n]
memo[n] = fib_memo(n - 1, memo, counter) + fib_memo(n - 2, memo, counter)
return memo[n]
c1, c2 = [0], [0]
print(fib_naive(30, c1), c1[0]) # 832040 2692537
print(fib_memo(30, {}, c2), c2[0]) # 832040 59Caching reduces about 2.7 million calls to 59, so the running time drops from exponential to linear.
Optimal substructure and its limits
Optimal substructure means you can build the best answer from the best answers to smaller pieces. Shortest paths have it. If the shortest route from A to C passes through B, then its A-to-B part must be a shortest A-to-B route. Otherwise you could swap in a shorter one.
Not every optimization problem has it. The longest simple path (no repeated vertices) does not. The best path from A to C through B may use vertices that the best B-to-C path also needs, so the two subpaths cannot be chosen independently. The subproblems interfere, and DP does not apply directly.
The standard recipe
- Define the state. Say in words what dp[i], dp[i][j] or similar means, for example "the best value using the first i items".
- Write the recurrence. Express a state in terms of smaller states by trying each possible last (or first) choice.
- Set the base cases. These are the smallest states, answered directly.
- Fix the evaluation order. Every state must be computed after the states it depends on.
- Read off the answer. It is usually one specific state, such as dp[n].
The running time follows from the structure:
time = (number of states) × (work per transition)
Fibonacci has n states and O(1) work each, giving O(n). Later chapters apply the same formula. For 0/1 knapsack it gives O(nW) and for LCS it gives O(mn). In GATE questions, counting states and transitions is often faster than tracing the whole table.
Two ways to implement it
- Top-down (memoization). Write the natural recursion and cache results. It computes only the states that are reached, but recursion depth can overflow the stack.
- Bottom-up (tabulation). Fill a table in dependency order with loops. It has no recursion overhead and often lets you keep only the last row or few values.
def fib_table(n):
if n < 2:
return n
prev, cur = 0, 1
for _ in range(2, n + 1):
prev, cur = cur, prev + cur
return cur
print(fib_table(30)) # 832040Because F(n) depends only on the two previous values, the table shrinks from O(n) to O(1) space. The next chapters cover the trade-offs of the two styles in detail.
Common errors
- Using DP when subproblems do not overlap. The table is then pure overhead.
- Memoizing a function whose result also depends on a mutable argument that is not part of the cache key.
- Treating greedy-looking problems as DP, or the reverse. Coin change with denominations {1, 3, 4} and target 6 shows why: greedy picks 4 + 1 + 1 (three coins), while 3 + 3 uses two.
- Confusing the number of subproblems with the number of recursive calls. Memoization bounds the first, and the second is at most states times branching factor.
Exercise
A recursive function f(i, j) is called with i from 0 to n and j from 0 to m. Each call makes three further calls to f with smaller arguments and does O(1) other work. With memoization, what is the running time? Does the answer change if the function also needs the set of already visited cells to be correct?
Show answer
There are (n+1)(m+1) distinct states and each does O(1) work beyond its three lookups, so the time is O(nm). If correctness depends on the visited set, that set becomes part of the state. The number of states grows to roughly nm times the number of possible subsets, which is exponential, so the DP is no longer polynomial.