Module 7 · Lesson 1 · ~30 min

Dynamic programming — first principles

DP scares people because the textbook starts with the answer. Let's build it the other way: start from naive recursion, notice the wasted work, cache it, and turn the cache into a table. Every DP problem starts that way.

The metaphor: the breadcrumb trail

Imagine a long hike where the trail forks repeatedly. You're handed a paper trail-map at every fork: "from here, the shortest path is X miles." You don't recompute. You read the breadcrumb someone (past you) left.

That's DP. You leave a breadcrumb at every subproblem the first time you compute it. When the same subproblem comes up again, you read the breadcrumb instead of recomputing.

The metaphor

DP is "the answer to this subproblem, written down so I don't redo it." The whole technique is a trick to recognize when the same subproblem is being asked over and over.

The two ingredients

A problem is solvable by DP if and only if it has both:

  1. Optimal substructure — the optimal answer can be built from optimal answers to subproblems.
  2. Overlapping subproblems — the same subproblems get re-solved many times in a naive recursion.

If you have only optimal substructure (no overlap), you have divide-and-conquer — like mergesort. If you have neither, you don't have DP, you have brute force.

The progression — climbing stairs

"You can climb 1 or 2 stairs at a time. How many distinct ways to reach step n?" Walk through the four versions of solving this — they map directly to how you'll think about every DP problem in an interview.

Stage 1 — naive recursion

def stairs(n):
    if n <= 1: return 1
    return stairs(n - 1) + stairs(n - 2)
# O(2^n) — same as Fibonacci
function stairs(n) {
  if (n <= 1) return 1;
  return stairs(n - 1) + stairs(n - 2);
}
// O(2^n) — same as Fibonacci
function stairs(n: number): number {
  if (n <= 1) return 1;
  return stairs(n - 1) + stairs(n - 2);
}
// O(2^n) — same as Fibonacci

Stage 2 — memoize (top-down DP)

def stairs(n, memo={}):
    if n <= 1: return 1
    if n in memo: return memo[n]
    memo[n] = stairs(n - 1, memo) + stairs(n - 2, memo)
    return memo[n]
# O(n) — each subproblem solved once
const memo = new Map();
function stairs(n) {
  if (n <= 1) return 1;
  if (memo.has(n)) return memo.get(n);
  const r = stairs(n - 1) + stairs(n - 2);
  memo.set(n, r);
  return r;
}
// O(n) — each subproblem solved once
const memo = new Map<number, number>();
function stairs(n: number): number {
  if (n <= 1) return 1;
  if (memo.has(n)) return memo.get(n)!;
  const r = stairs(n - 1) + stairs(n - 2);
  memo.set(n, r);
  return r;
}
// O(n) — each subproblem solved once

Stage 3 — tabulate (bottom-up DP)

def stairs(n):
    dp = [1] * (n + 1)
    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]
# O(n) time, O(n) space
function stairs(n) {
  const dp = new Array(n + 1).fill(1);
  for (let i = 2; i <= n; i++) {
    dp[i] = dp[i - 1] + dp[i - 2];
  }
  return dp[n];
}
// O(n) time, O(n) space
function stairs(n: number): number {
  const dp = new Array(n + 1).fill(1);
  for (let i = 2; i <= n; i++) {
    dp[i] = dp[i - 1] + dp[i - 2];
  }
  return dp[n];
}
// O(n) time, O(n) space

Stage 4 — space optimize

def stairs(n):
    a, b = 1, 1
    for _ in range(n):
        a, b = b, a + b
    return a
# O(n) time, O(1) space — only the last 2 cells matter
function stairs(n) {
  let a = 1, b = 1;
  for (let i = 0; i < n; i++) {
    [a, b] = [b, a + b];
  }
  return a;
}
// O(n) time, O(1) space — only the last 2 cells matter
function stairs(n: number): number {
  let a = 1, b = 1;
  for (let i = 0; i < n; i++) {
    [a, b] = [b, a + b];
  }
  return a;
}
// O(n) time, O(1) space — only the last 2 cells matter
The four-stage ladder

For every DP problem, climb the ladder: recurse → memoize → tabulate → optimize space. If you can do all four out loud, the interviewer is satisfied. Most candidates only do one or two.

The state-design question

The hardest part of DP isn't the code — it's deciding what your state is. The state is the input to your subproblem function.

Useful question: "What do I need to know to make the next decision?" Whatever that is, that's your state.

ProblemStateTransition
Climbing stairsi (current step)dp[i] = dp[i-1] + dp[i-2]
Coin change (min coins)amountdp[a] = min over coins c of dp[a - c] + 1
Longest common subsequence(i, j) indices in two stringsmatch → dp[i+1][j+1] + 1; else max
0-1 Knapsack(item index, capacity remaining)take it or skip it
Edit distance(i, j) indicesinsert / delete / replace + 1

How to recognize a DP problem in the wild

  1. The problem asks for "the optimal X" — minimum, maximum, count of ways, fewest, longest.
  2. You can frame the answer as "make a choice; the rest is the same problem on a smaller input."
  3. The naive recursion has overlapping subproblems.

If you see all three, it's DP. Walk the four-stage ladder.

Interview reality

You don't have to write the optimized version first. Write the recursive version, narrate "this is exponential because of overlapping subproblems," memoize it, then mention "I could tabulate this bottom-up if you want." The interviewer often says "good, that's enough" and moves on. They want to see you climb the ladder, not magic the answer.

Try it: coin change (minimum coins)