Dynamic Programming

Solve a problem once for each smaller version of it, store each answer, and build the full answer from the stored ones.

Overview

Dynamic programming (DP) is a way to solve a problem by solving smaller versions of it first. Each smaller version is a subproblem. You solve each subproblem once, store its answer, and reuse the stored answer every time it comes up again. Richard Bellman introduced the method and its name in the 1950s.

DP fits when a problem has two properties. The first is overlapping subproblems: a plain recursive solution asks the same question many times. The second is optimal substructure: the best answer to the whole problem is built from the best answers to its subproblems. DP sits between greedy and backtracking: it explores every choice like backtracking, but only once per state.

Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

Why plain recursion repeats work

The rule: when a recursive solution asks the same question many times, store each answer the first time and look it up after that.

The Fibonacci numbers show it. Each Fibonacci number is the sum of the two before it, so a recursive fib(n) calls fib(n - 1) and fib(n - 2). The tree below shows every call that plain recursion makes to get fib(4).

Every yellow call repeats work that another branch has already done. The number of calls explodes as n grows.

  • n = 10: plain recursion makes 177 calls; a stored answer per value needs 11 computations.
  • n = 20: 21,891 calls against 21.
  • n = 30: 2,692,537 calls against 31.

With a stored answer per value, fib(n) needs only n + 1 distinct computations.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio