Skip to content

What is Dynamic Programming?

Patterns·7 min·Python code

Dynamic programming splits a problem into overlapping subproblems and stores every answer, so no subproblem gets solved twice. That cache cuts exponential recursion down to polynomial time.

Overlapping Subproblems and Optimal Substructure

Dynamic programming is recursion plus a notebook. Plain recursion for Fibonacci calls fib(4) and fib(3) from fib(5), then fib(4) calls fib(3) again, so the same call repeats many times.

Write down every answer the first time you compute it, and later calls become free lookups. Exponential blowup disappears.

Two conditions must hold. Overlapping subproblems means the recursion revisits the same inputs, unlike merge sort, whose halves never repeat. Optimal substructure means an optimal answer to the problem is built from optimal answers to its parts.

When both conditions hold, caching cuts exponential work to polynomial.

Memoization vs Tabulation in Dynamic Programming

Memoization works top down. You keep the natural recursion, store every result in a cache keyed by the subproblem arguments and check the cache before computing. It visits only the subproblems you reach, and you derive it straight from a brute force recursion.

Tabulation works bottom up. You drop recursion and fill a table in dependency order, from the base cases to the final answer. That avoids call stack limits and makes space savings obvious, because you often need only the last row or two, so an O(n × W) table shrinks to O(W).

Choose memoization when the recurrence is clear and few states are reachable. Choose tabulation when you want control over fill order and memory.

Classic Dynamic Programming Problems to Learn First

Fibonacci is the smallest example, with one number n as state and every term adding the two before it. Memoizing drops the cost from O(2ⁿ) to O(n).

Knapsack and longest common subsequence add a second dimension. Knapsack state is the item index and remaining capacity, and every cell takes the better of skipping or taking the item, which shows why greedy algorithms fail where DP wins.

LCS state is a position in string A and a position in string B, and every cell extends a match or drops one character. Edit distance and diff tools use the same table shape.

Watch these three tables fill and most other problems become variations on one move. Define the state, write the recurrence, pin the base cases and choose the fill order.

Practise that move on CodeStory's dynamic programming practice problems.

Dynamic Programming Code Example in Python

pythonBottom up 0/1 knapsack in Python where every cell reuses two solved subproblems.

def knapsack(weights, values, capacity):
    n = len(weights)
    # dp[i][w] = highest value using the first i items within weight limit w
    dp = [[0] * (capacity + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        wt, val = weights[i - 1], values[i - 1]
        for w in range(capacity + 1):
            dp[i][w] = dp[i - 1][w]                      # skip item i
            if wt <= w:                                  # or take item i
                dp[i][w] = max(dp[i][w], dp[i - 1][w - wt] + val)
    return dp[n][capacity]

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Dynamic Programming Time and Space Complexity

TimeO(states × transitions), like O(n) for Fibonacci, O(n × W) for knapsack and O(m × n) for LCS
SpaceO(states) for the table, with rolling rows cutting Fibonacci to O(1), knapsack to O(W) and LCS to O(min(m, n))

DP replaces exponential recursion, like O(2ⁿ) for Fibonacci, with polynomial time. Input shape does not change the bound, because the full state space is traversed.

Watch Dynamic Programming Step by Step

Seeing the table fill cell by cell shows how states build on one another. Follow any of these one step at a time.

When to Use Dynamic Programming

  • Naive recursion recomputes the same inputs again and again, like Fibonacci or recursive knapsack, and you want a cache to cut the exponential blowup.
  • Problems ask for a count of ways, a min or max cost or whether a target is reachable over a bounded set of states, like coin change, longest increasing subsequence or edit distance.
  • Choices are constrained and you need the true global optimum, not a greedy guess, as in 0/1 knapsack where greedy provably fails.
  • You work over sequences or grids where every step depends on answers to smaller subproblems.

Mistakes to Avoid

  • Using DP when subproblems never repeat or optimal substructure fails. Without overlap memoization adds overhead, and without substructure the answer is wrong.
  • Leaving a dimension out of the state, like remaining capacity in knapsack, which returns wrong results without any error.
  • Mixing up greedy and DP. Greedy gives wrong answers on 0/1 knapsack and coin change with arbitrary denominations, and off by one errors in base case rows or columns break the table when you convert recursion to tabulation.

Dynamic Programming FAQs

Is dynamic programming hard to learn?

Difficulty is pattern recognition more than maths. Learn the two signals, overlapping subproblems and optimal substructure, then practise defining state and recurrence on a dozen classic problems. Watching the table fill makes the recurrence click.

What is the difference between memoization and tabulation?

Both cache subproblem results. Memoization is top down, keeping recursion with a cache keyed by arguments, and tabulation is bottom up, filling a table from the base cases. Time complexity matches, tabulation avoids call stack limits and memoization is easier to derive from brute force.

When should I use dynamic programming instead of greedy?

Use greedy when a local choice provably leads to the global optimum, like activity selection or Huffman coding. Use DP when you must weigh combinations of choices, like 0/1 knapsack or coin change with arbitrary denominations. If you cannot prove the greedy choice is safe, choose DP.

What is the time complexity of a dynamic programming solution?

Count the distinct states and multiply by the cost of one transition. Fibonacci has O(n) states with O(1) transitions, so it costs O(n). 0/1 knapsack costs O(n × W) and LCS costs O(m × n). Space equals the table size, and rolling rows often cut it.

How do I know if a problem needs dynamic programming?

Check for overlapping subproblems and optimal substructure. Problems that ask for a count of ways, a min or max cost or whether a target is reachable, with choices that depend on smaller subproblems, point to dynamic programming.

What are the steps to solve a dynamic programming problem?

Define the state, write the recurrence, pin the base cases and choose the fill order. Then add a cache for memoization or build the table for tabulation.

How do I practise dynamic programming on CodeStory?

Watch Fibonacci, 0/1 knapsack and longest common subsequence in CodeStory's visualisers, then solve CodeStory's dynamic programming practice problems.

Related Guides

Guides are step one. In a CodeStory batch you code the recurrence yourself, then explain every state in a scored mock round.

Talk to a Mentor

Stuck on Dynamic Programming? Get a Free Callback

Tell CodeStory which state or recurrence confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first recurrence to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.