Lesson 146 of 296
Dynamic programming: 1D
What you will learn
- What dynamic programming is and when to use it
- State, transition and base cases
- Top-down (memoization) vs bottom-up (tabulation)
- Climbing Stairs
- House Robber
- Coin Change
- Word Break
- A method for solving any DP problem
On this page
What is dynamic programming?
Dynamic programming (DP) solves a problem by breaking it into smaller subproblems, solving each subproblem once, and storing the answers to build bigger answers.
Use DP when a problem has:
- Overlapping subproblems: the same smaller question is asked many times (like naive Fibonacci, Lesson 134).
- Optimal substructure: the best answer can be built from the best answers to smaller parts.
Typical wording: "how many ways", "minimum cost", "maximum value", "is it possible".
The three things to define
| Part | Question | Climbing stairs example |
|---|---|---|
| State | What does dp[i] mean? | Number of ways to reach step i |
| Transition | How do I compute dp[i] from smaller states? | dp[i] = dp[i-1] + dp[i-2] |
| Base cases | What are the smallest answers? | dp[0] = 1, dp[1] = 1 |
Defining the state clearly in words is the most important step. Say it out loud in the interview.
Top-down vs bottom-up
| Top-down (memoization) | Bottom-up (tabulation) | |
|---|---|---|
| How | Recursion + cache (Lesson 79) | Loop filling a table from small to large |
| Pros | Natural to write from the recursive idea; only solves needed subproblems | No recursion depth limit; often easy to reduce memory |
| Cons | Recursion overhead and stack depth | Must work out the order to fill the table |
A good interview approach: explain the recursive idea, write top-down if it is easier, then convert to bottom-up and reduce memory if asked.
Climbing Stairs
Problem (LeetCode 70): you can climb 1 or 2 steps at a time. How many different ways to reach step n?
To reach step i, your last move was from step i−1 or step i−2. So ways(i) = ways(i−1) + ways(i−2). Only the last two values are needed, so O(1) memory:
function climbStairs(n: number): number {
let twoBack = 1;
let oneBack = 1;
for (let i = 2; i <= n; i++) {
const current = oneBack + twoBack;
twoBack = oneBack;
oneBack = current;
}
return oneBack;
}O(n) time, O(1) space. (It is the Fibonacci sequence.)
House Robber
Problem (LeetCode 198): houses in a row with money; you cannot rob two adjacent houses. Maximum money?[2, 7, 9, 3, 1] → 12 (2 + 9 + 1).
State: dp[i] = best total from the first i houses.
Transition: at house i, either skip it (dp[i-1]) or rob it (dp[i-2] + nums[i]). Take the bigger.
function rob(nums: number[]): number {
let twoBack = 0;
let oneBack = 0;
for (const money of nums) {
const current = Math.max(oneBack, twoBack + money);
twoBack = oneBack;
oneBack = current;
}
return oneBack;
}O(n) time, O(1) space. (House Robber II, LeetCode 213, puts the houses in a circle: run this twice, once without the first house and once without the last.)
Coin Change
Problem (LeetCode 322): coin values and an amount. The fewest coins to make the amount (unlimited coins of each value), or -1 if impossible.coins = [1, 2, 5], amount = 11 → 3 (5 + 5 + 1).
Greedy fails in general (Lesson 145), so use DP.
State: dp[a] = fewest coins to make amount a.
Transition: for each coin c not bigger than a, dp[a] = min(dp[a], dp[a - c] + 1).
Base: dp[0] = 0. Everything else starts as Infinity ("not possible yet").
function coinChange(coins: number[], amount: number): number {
const dp = new Array<number>(amount + 1).fill(Infinity);
dp[0] = 0;
for (let a = 1; a <= amount; a++) {
for (const coin of coins) {
if (coin <= a && dp[a - coin]! + 1 < dp[a]!) {
dp[a] = dp[a - coin]! + 1;
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount]!;
}O(amount × number of coins) time, O(amount) space.
Related: Coin Change II (LeetCode 518) counts the number of ways. Loop over coins in the outer loop so each combination is counted once regardless of order.
Word Break
Problem (LeetCode 139): can the string be split into words from a dictionary?s = "leetcode", wordDict = ["leet", "code"] → true.
State: dp[i] = can the first i characters be split?
Transition: dp[i] is true if there is some j < i where dp[j] is true and s.slice(j, i) is a dictionary word.
function wordBreak(s: string, wordDict: string[]): boolean {
const words = new Set(wordDict);
const maxLength = Math.max(0, ...wordDict.map((w) => w.length));
const dp = new Array<boolean>(s.length + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= s.length; i++) {
for (let j = Math.max(0, i - maxLength); j < i; j++) {
if (dp[j] && words.has(s.slice(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length]!;
}Limiting j to the longest word length saves work. O(n × L) checks, each with an O(L) slice, for word length L.
A method for any DP problem
- Write the brute-force recursion (try every choice).
- Notice repeated subproblems in the recursion tree.
- Define the state in one sentence.
- Write the transition and base cases.
- Add memoization (top-down) or fill a table (bottom-up).
- Check the order: every state you read must already be computed.
- Reduce memory if only the last few states are used.
- State the complexity: number of states × work per state.
How to say it in an interview
"Dynamic programming applies when subproblems overlap and the optimal answer is built from optimal sub-answers. I define the state in words, the transition, and the base cases, then implement it top-down with memoization or bottom-up with a table, and reduce space when only the last few states matter. For example House Robber chooses between skipping a house or robbing it plus the best from two back, and Coin Change takes the minimum over coins of one plus the answer for the remaining amount. Complexity is the number of states times the work per state."
Key words
| Word | Meaning |
|---|---|
| Dynamic programming | Solving subproblems once and reusing their answers |
| Overlapping subproblems | The same smaller problem appearing many times |
| Optimal substructure | The best answer built from best sub-answers |
| State | What one table entry means |
| Transition | The formula linking a state to smaller states |
| Memoization / tabulation | Top-down with a cache / bottom-up with a table |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.