← Learning Hub
Advanced

Dynamic Programming

Dynamic programming (DP) solves a problem by breaking it into overlapping smaller problems and saving each answer so it's never worked out twice.

DP solves problems where the same smaller questions repeat, by saving their answers. It's a favourite interview topic because it tests clear thinking about subproblems.

Fibonacci: from 2^n to n

Example
You can edit this code.

Coin change: fewest coins

Example
You can edit this code.

0/1 knapsack: best value within a budget

Example
You can edit this code.

Longest common subsequence

Example
You can edit this code.
Steps for any DP problem: (1) define what dp[x] means in words, (2) write how it's built from smaller answers, (3) set the starting values, (4) decide the loop order.
Key points
  • Define dp[x] in words first.
  • Build from smaller answers.
  • Classics: coin change, knapsack, LCS.

📝 Test yourself

1. What is the key idea of DP?
2. In 0/1 knapsack with a 1-D array, why loop the budget backwards?
3. Fill in: storing results of recursive calls is called