AlgoViz

Dynamic programming: core concepts

medium 18 min

Dynamic programming solves a problem by breaking it into smaller subproblems, solving each distinct subproblem once and storing the answer.

Chapter mnemonic

Four dynamic programming decisions

Label the jars. Fill the starters. Follow the recipe. Cook in order.

What does the recipe tell you, and why cook some jars first?

The recurrence combines dependency states. The computation order makes those answers available first.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Solve each subproblem once, write it down, look it up after.

A notebook of answers. The first time someone asks 2 + 2 you work it out and write 4 down; every later time you just read it. DP is a notebook for subproblems: the work depends on how many different questions exist, not on how often they are asked.

Cheat sheet

Needs
Overlapping subproblems + optimal substructure
Recipe
State, transition, base cases, order
Time
States × work per state
Space
States kept (plus stack if top-down)
Top-down
Recursion + memo, reachable states only
Bottom-up
Loops + table, no depth limit
Rolling
Reads last k states: O(k) space
fib(10) calls
177 naive, 19 memoised
Unique paths m × n
O(mn) time, O(n) space

Spot it when you see

  • Count the number of ways to do something.
  • Minimum cost, maximum profit, longest or shortest sequence.
  • Can you reach the end, make the amount, or split the set?
  • Each choice limits the choices that follow, so greedy is risky.
  • A brute-force recursion repeats the same arguments in different branches.

Tricks that stick

  • MOST: Memoise to avoid recomputation, Optimal substructure, Subproblems overlap, Table stores results.
  • The recursion already has everything: its parameters are the state, its recursive line is the transition, its stopping test is the base case.
  • Finish the sentence dp[i] is the ... before writing any code.
  • Identify, Define, Create, Solve: spot the DP, define the subproblems, create the table or cache, solve in order.

Do not forget

  • A state that leaves out a variable the answer depends on.
  • Filling cells before their inputs are ready.
  • A table of n cells when the answer lives at index n.
  • A mutable default argument used as the memo.
  • Memoised recursion that is too deep for the recursion limit.
  • Rolling the table and then needing the path back.