Sign in

Dynamic programming, from overlapping subproblems to state spaces

Identify optimal substructure, eliminate redundant calculations with memoization and tabulation, and design state transitions for complex optimization problems.

MonksBit Desk

November 17, 2026 · 8 min read · 148 views

Read

Dynamic programming is an algorithm design technique that solves complex optimization and counting problems by breaking them into simpler subproblems, solving each subproblem once, and storing their results to avoid redundant work. It applies specifically to problems exhibiting optimal substructure and overlapping subproblems.

You will need. Basic recursion and call stacks · Time and space complexity using Big-O notation · Familiarity with arrays and hash maps

How well do you know this already?

The full lesson

Level 1 · Beginner: Understanding caching and subproblem recurrence

Many computations naturally divide into smaller tasks of the exact same form. A standard example is computing the Fibonacci sequence, where each term is the sum of the previous two terms: F(n) = F(n-1) + F(n-2), with base values F(0) = 0 and F(1) = 1. If you write this directly as a naive recursive function, calculating F(5) requires calculating F(4) and F(3). But calculating F(4) also requires F(3) and F(2). Notice that F(3) is computed twice independently, along with all of its sub-branches.

As n increases, this redundant recalculation explodes exponentially. The total number of operations roughly doubles with every increment of n, forming a massive recursion tree where the vast majority of calls duplicate work already completed in earlier branches. We call this condition overlapping subproblems.

The fix is conceptually straightforward: write down the answer to each subproblem the first time you compute it. The next time the function asks for that exact input, return the saved answer directly instead of re-evaluating the entire tree. This technique of caching the return values of recursive calls is called memoization, or top-down dynamic programming.

Consider calculating F(4) by hand. First, check if F(4) is recorded; it is not. Recurse down to F(3), then down to F(2), then down to F(1) and F(0). F(1) returns 1 and F(0) returns 0. Compute F(2) = 1 + 0 = 1, and save 1 into your record under key 2. Now return to F(3), which needs F(2) and F(1). Instead of recursing into F(2) again, look up its value: 1. Thus F(3) = 1 + 1 = 2, which you store. Finally, F(4) combines stored F(3) and stored F(2) to produce 3, making only linear progress through distinct states.

Top-down memoized Fibonacci implementation

def fib_memo(n: int, memo: dict[int, int] | None = None) -> int:    if memo is None:        memo = {}    if n in memo:        return memo[n]    if n <= 0:        return 0    if n == 1:        return 1    memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)    return memo[n]if __name__ == "__main__":    print(fib_memo(10))  # Output: 55

Key takeaways

  • Overlapping subproblems mean the same computational state is reached multiple times across a recursion tree.
  • Memoization stores results the first time they are encountered to short-circuit repeated work.
  • Optimal substructure guarantees that the best solution to a problem contains within it the best solutions to its subproblems.

Level 2 · Intermediate: Tabulation and structural state transitions

While memoization works top-down from the primary problem to the base cases, dynamic programming can also proceed bottom-up. This approach is called tabulation. Instead of relying on the system call stack, tabulation allocates an array or table, fills in the base cases first, and iteratively builds answers toward the target.

To design a bottom-up solution, you define three components: the state, the base cases, and the recurrence relation. The state is the set of parameters that uniquely identifies a subproblem, such as an array index or a remaining capacity. The recurrence relation is the mathematical equation relating larger states to previously computed smaller states.

Consider the Coin Change problem: given an integer array of coin denominations and a target amount, find the minimum number of coins needed to make that exact amount. If no combination can make the amount, return -1. Here, let dp[a] be the minimum coins needed to make amount a. The base case is dp[0] = 0, because zero coins are needed to make an amount of zero. For every other amount a, the recurrence relation is dp[a] = 1 + min(dp[a - c]) across every coin denomination c where a - c is greater than or equal to 0.

Tabulation avoids the overhead of recursion and prevents stack overflow errors on large inputs. It also clarifies data dependencies, making it easier to verify correctness and analyze exact space requirements.

Bottom-up tabulation for the coin change problem

def coin_change(coins: list[int], amount: int) -> int:    if amount < 0:        return -1    if amount == 0:        return 0    # Initialize table with infinity; table size is amount + 1    inf = float("inf")    dp = [inf] * (amount + 1)    dp[0] = 0    for current_amount in range(1, amount + 1):        for coin in coins:            if current_amount - coin >= 0:                dp[current_amount] = min(                    dp[current_amount],                    dp[current_amount - coin] + 1                )    return int(dp[amount]) if dp[amount] != inf else -1if __name__ == "__main__":    print(coin_change([1, 2, 5], 11))  # Output: 3    print(coin_change([2], 3))          # Output: -1

Key takeaways

  • Tabulation processes states iteratively from base cases up to the target answer.
  • Explicit state definitions and boundary initializations eliminate call stack overhead.
  • Unreachable states are represented using placeholder values such as infinity.

Level 3 · Advanced: Multi-dimensional states, space compression, and boundaries

Complex problems require multi-dimensional state descriptions. For instance, the classic 0/1 Knapsack problem defines state dp[i][w] as the maximum value achievable considering the first i items under weight limit w. The transition chooses whether to skip or include item i: dp[i][w] = max(dp[i-1][w], dp[i-1][w - weight[i]] + value[i]). This yields an O(N * W) time and space complexity, where N is the item count and W is the capacity.

When inspecting the dependency graph of dp[i][w], each row i depends exclusively on the previous row i-1. This structural property enables space compression. Instead of retaining the entire two-dimensional table, we can maintain only a single one-dimensional array of size W + 1. By iterating the weight backward from W down to weight[i], we read the old values from row i-1 before overwriting them with values for row i, reducing auxiliary space from O(N * W) to O(W).

Dynamic programming appears extensively in production systems, such as diff utilities calculating Longest Common Subsequence (LCS), text justification engines, DNA sequence alignment tools using the Needleman-Wunsch algorithm, and database query planners evaluating optimal join orderings. However, dynamic programming fails when subproblems lack optimal substructure, such as finding the longest simple path in an arbitrary directed graph, where choices in one subproblem constrain the validity of choices in another.

Space-optimized 0/1 knapsack implementation

def knapsack_01(weights: list[int], values: list[int], capacity: int) -> int:    n = len(weights)    if n == 0 or capacity <= 0:        return 0    # dp[w] stores max value achievable with capacity w    dp = [0] * (capacity + 1)    for i in range(n):        w_i = weights[i]        v_i = values[i]        # Traverse backwards to preserve previous row data without overwrite        for w in range(capacity, w_i - 1, -1):            dp[w] = max(dp[w], dp[w - w_i] + v_i)    return dp[capacity]if __name__ == "__main__":    w = [1, 3, 4, 5]    v = [1, 4, 5, 7]    c = 7    print(knapsack_01(w, v, c))  # Output: 9 (items with weights 3 and 4)

Key takeaways

  • Multi-dimensional states track multiple independent constraints like item index and remaining capacity.
  • Space compression reduces memory complexity by recycling arrays when state transitions depend only on immediately preceding stages.
  • Iterating backwards prevents overwriting states from the current iteration when using a single dimensional buffer.

Complexity

  • Time: O(N * W)
  • Space: O(W)

For the 0/1 Knapsack example, computing the result requires visiting every item up to N and iterating through capacities up to W, producing O(N * W) runtime across best, average, and worst cases. The space complexity is O(W) because the memory is compressed into a single array of size W + 1.

Common mistakes

  • Failing to verify optimal substructure, attempting to apply dynamic programming to problems where local optimal choices invalidate global state consistency.
  • Updating tabulated space-optimized arrays in the forward direction instead of backward, which accidentally allows items to be used multiple times like an unbounded knapsack.
  • Improper initialization of base cases or sentinel values, such as using 0 instead of positive infinity for minimum-cost optimization problems.
  • Neglecting stack overflow limits when using top-down recursion on deep input instances without increasing recursion limits.

Practice problems

  1. Climbing Stairs (easy). Hint: Relate the number of ways to reach step n to the ways to reach steps n-1 and n-2.
  2. Longest Increasing Subsequence (medium). Hint: Let dp[i] represent the length of the longest increasing subsequence ending at index i, checking all previous indices j where nums[j] is smaller than nums[i].
  3. Edit Distance (hard). Hint: Use a two-dimensional state dp[i][j] representing the minimum operations to convert word1 prefix of length i into word2 prefix of length j, comparing characters at each step.

Summary

Dynamic programming turns exponential recursive computations into polynomial algorithms by storing and reusing intermediate answers. The progression begins with recognizing overlapping subproblems through top-down memoization, converts to bottom-up iterative tabulation for efficiency, and culminates in state compression across multi-dimensional state graphs.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!