intermediatealgorithms

Dynamic Programming

Dynamic Programming

Dynamic programming (DP) is a technique for solving problems by breaking them into smaller overlapping subproblems, solving each subproblem once, and reusing the stored result whenever the same subproblem appears again. It turns exponential-time recursive solutions into polynomial-time ones by trading a small amount of memory for a large amount of repeated work.

When Does DP Apply?

A problem is a good candidate for dynamic programming when it has both of these properties:

  1. Overlapping subproblems: the same smaller problems are solved repeatedly. (If subproblems never repeat, plain divide-and-conquer is enough.)
  2. Optimal substructure: an optimal solution to the whole problem can be built from optimal solutions to its subproblems.

Two Ways to Apply DP

Top-Down (Memoization)

Write the natural recursion, then cache each result the first time it is computed. Subsequent calls return the cached value instead of recomputing.

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n: int) -> int:
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

Bottom-Up (Tabulation)

Fill a table starting from the base cases and building up to the answer. There is no recursion — just a loop that computes each entry from earlier entries.

def fib(n: int) -> int:
    if n < 2:
        return n
    dp = [0] * (n + 1)
    dp[1] = 1
    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]

Both run in O(n) time. The bottom-up version is what the interactive visualizer animates: each cell dp[i] is filled from the two cells before it.

Worked Example: Fibonacci

The Fibonacci sequence is the classic first example because the naive recursion is spectacularly wasteful, and DP fixes it cleanly.

The naive recursion recomputes the same values over and over:

                     fib(5)
              /                  \
          fib(4)                fib(3)
         /      \              /      \
     fib(3)    fib(2)      fib(2)    fib(1)
     /    \    /    \      /    \
 fib(2) fib(1) ...        ...

fib(3) is computed twice, fib(2) three times, and it gets worse as n grows.

Dynamic programming computes each value exactly once. Building the table bottom-up:

i:      0    1    2    3    4    5    6    7
dp[i]:  0    1    1    2    3    5    8   13
                  ^
                  dp[2] = dp[1] + dp[0] = 1 + 0 = 1

Each entry is the sum of the two preceding entries: dp[i] = dp[i-1] + dp[i-2]. The final answer is the last cell.

Complexity Analysis

Time Complexity: O(n)

Naive recursion makes roughly fib(n) calls, which grows as O(2^n). DP computes each of the n + 1 table entries once, so the runtime is linear.

ApproachTimeSpace
Naive recursionO(2^n)O(n) stack
Memoization (top-down)O(n)O(n) + O(n) stack
Tabulation (bottom-up)O(n)O(n)
Tabulation, rolling variablesO(n)O(1)

Space Complexity: O(n)

The DP table stores one value per index. When only the last two values are needed — as in Fibonacci — the table can be replaced by two rolling variables to reach O(1) space:

def fib(n: int) -> int:
    prev, curr = 0, 1
    for _ in range(n):
        prev, curr = curr, prev + curr
    return prev

Memoization vs. Tabulation

AspectMemoization (top-down)Tabulation (bottom-up)
StyleRecursion + cacheIterative table fill
OrderComputes only needed subproblemsComputes all subproblems in order
OverheadRecursion/call-stack costNo recursion
ReadabilityMirrors the natural recurrenceRequires choosing a fill order
RiskStack overflow for large nNone

Choose memoization when the recurrence is easy to express and not all subproblems are needed. Choose tabulation when you want to avoid recursion or reduce space with a rolling window.

More Examples

Climbing Stairs

Count the ways to climb n steps taking 1 or 2 steps at a time — the same recurrence as Fibonacci.

def climb_stairs(n: int) -> int:
    if n < 2:
        return 1
    dp = [0] * (n + 1)
    dp[0] = dp[1] = 1
    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]

Coin Change (Minimum Coins)

Find the fewest coins that sum to amount, or -1 if impossible.

def coin_change(coins: list[int], amount: int) -> int:
    dp = [float("inf")] * (amount + 1)
    dp[0] = 0
    for value in range(1, amount + 1):
        for coin in coins:
            if coin <= value:
                dp[value] = min(dp[value], dp[value - coin] + 1)
    return dp[amount] if dp[amount] != float("inf") else -1

When to Use Dynamic Programming

  • Counting problems: number of ways to reach a state (climbing stairs, paths in a grid).
  • Optimization with substructure: shortest path, minimum cost, longest subsequence.
  • Sequence problems: longest common subsequence, edit distance, longest increasing subsequence.
  • Resource allocation: knapsack, partitioning, scheduling.

When to Avoid It

  • No overlapping subproblems: plain divide-and-conquer (e.g. merge sort) is simpler and just as fast.
  • A greedy choice is provably optimal: greedy is faster and uses less memory.
  • The state space is too large: if the table would not fit in memory, consider approximation or a different formulation.

Key Properties

PropertyValue
ParadigmReuse of overlapping subproblems
RequiresOptimal substructure
StylesTop-down (memoization), bottom-up (tabulation)
Typical timePolynomial (often O(n) or O(n·m))
SpaceSize of the state table (often reducible)