Dynamic Programming for Beginners

By Published 8 min read

Dynamic Programming for Beginners

Introduction:

At the end of the recursion lesson we saw something surprising. A simple recursive Fibonacci function needed 242,785 calls to compute fib(25), but after we stored each answer in a Map, it needed only 49. That small trick is the heart of dynamic programming (DP).

Dynamic programming is a way of solving problems by breaking them into smaller sub-problems, solving each sub-problem only once, and saving its answer so it can be reused. It turns many problems that would take exponential time into ones that take polynomial time, often just O(n) or O(n × m).

DP has a reputation for being hard, mostly because it is usually explained with formulas. In this lesson we will build it up step by step with small JavaScript examples, every one of them tested, and a simple recipe you can use on new problems.

When Can You Use Dynamic Programming?

A problem is a good fit for DP when it has two properties:

  • Overlapping sub-problems: the same smaller problem is solved many times. In Fibonacci, fib(5) needs fib(4) and fib(3), and fib(4) needs fib(3) again.
  • Optimal substructure: the best answer for the whole problem can be built from the best answers of its sub-problems. The shortest route from A to C through B is the shortest route from A to B plus the shortest route from B to C.

If sub-problems don’t overlap (as in merge sort, where each half is different), plain divide and conquer is enough. DP pays off when the same work would be repeated.

A useful hint: DP problems often ask for “the minimum…”, “the maximum…”, “the number of ways…” or “is it possible…”.

Two Ways to Write DP

1. Top-Down: Memoization:

Write the natural recursive solution, then add a cache. Before computing, check the cache; after computing, store the answer.

function fibMemo(n, memo = new Map()) {
  if (n < 2) return n;
  if (memo.has(n)) return memo.get(n);
  const v = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
  memo.set(n, v);
  return v;
}

2. Bottom-Up: Tabulation:

Instead of starting from the big problem, start from the smallest ones and fill a table (an array) up to the answer. No recursion is needed.

function fibTab(n) {
  if (n < 2) return n;
  const dp = new Array(n + 1).fill(0);
  dp[1] = 1;
  for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
  return dp[n];
}

3. Saving Space:

Each Fibonacci number only depends on the previous two, so we don’t need the whole table, just two variables:

function fibSmall(n) {
  if (n < 2) return n;
  let prev = 0, curr = 1;
  for (let i = 2; i <= n; i++) [prev, curr] = [curr, prev + curr];
  return curr;
}

console.log(fibMemo(50), fibTab(50), fibSmall(50));
// 12586269025 12586269025 12586269025

All three run in O(n) time. Memoization uses O(n) memory for the cache plus the call stack, tabulation uses O(n) for the table, and the last version uses O(1).

Which should you use? Memoization is often easier to write because it follows the recursive idea directly. Tabulation avoids deep recursion (and stack overflow) and is usually a little faster. In interviews, either is fine; start with whichever you find clearer.

A Five-Step Recipe

For any new DP problem, answer these five questions:

  1. State: what does dp[i] (or dp[i][j]) mean, in words? This is the most important step.
  2. Transition: how is dp[i] computed from smaller states?
  3. Base cases: which smallest states do you know directly?
  4. Order: in which order must the table be filled so the needed states are ready?
  5. Answer: which entry of the table is the final answer?

Let’s practise the recipe on classic problems.

Problem 1: Climbing Stairs

You are climbing a staircase with n steps. Each time you can climb 1 or 2 steps. In how many different ways can you reach the top?

  • State: ways(i) = number of ways to reach step i.
  • Transition: the last move to step i came either from step i - 1 (a 1-step) or from step i - 2 (a 2-step), so ways(i) = ways(i - 1) + ways(i - 2).
  • Base cases: ways(1) = 1, ways(2) = 2 (1+1 or 2).
  • Order: from small i to large. Answer: ways(n).

It’s Fibonacci in disguise:

function climbStairs(n) {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) [a, b] = [b, a + b];
  return b;
}

console.log(climbStairs(4), climbStairs(10)); // 5 89

For 4 steps the 5 ways are 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2.

Problem 2: Coin Change

Given coin values and an amount, find the fewest coins that add up to the amount, or -1 if it can’t be done.

  • State: dp[a] = fewest coins needed to make amount a.
  • Transition: try every coin c as the last coin: dp[a] = min(dp[a - c] + 1).
  • Base case: dp[0] = 0. Everything else starts at Infinity (not possible yet).
  • Answer: dp[amount].
function coinChange(coins, amount) {
  const dp = new Array(amount + 1).fill(Infinity);
  dp[0] = 0;
  for (let a = 1; a <= amount; a++) {
    for (const c of coins) {
      if (c <= a && dp[a - c] + 1 < dp[a]) dp[a] = dp[a - c] + 1;
    }
  }
  return dp[amount] === Infinity ? -1 : dp[amount];
}

console.log(coinChange([1, 5, 10, 25], 63)); // 6  (25 + 25 + 10 + 1 + 1 + 1)
console.log(coinChange([1, 3, 4], 6));       // 2  (3 + 3)
console.log(coinChange([2], 3));             // -1

Why not just take the biggest coin each time? That greedy approach works for normal currency, but not for every set of coins:

function greedyCoins(coins, amount) {
  let count = 0;
  for (const c of [...coins].sort((x, y) => y - x)) {
    count += Math.floor(amount / c);
    amount %= c;
  }
  return amount === 0 ? count : -1;
}

console.log(greedyCoins([1, 3, 4], 6)); // 3  (4 + 1 + 1), but the best is 2

DP tries every option for every amount, so it always finds the true minimum. The running time is O(amount × number of coins).

Problem 3: House Robber

Houses on a street hold some money. You can’t take money from two neighbouring houses. What is the most money you can collect?

At each house you have two choices: take it (then you must have skipped the previous house) or skip it (then take the best of the previous house’s two choices). We keep just two numbers as we walk along the street:

function rob(houses) {
  let take = 0, skip = 0;
  for (const money of houses) {
    [take, skip] = [skip + money, Math.max(take, skip)];
  }
  return Math.max(take, skip);
}

console.log(rob([2, 7, 9, 3, 1])); // 12  (2 + 9 + 1)

This “take it or leave it” pattern appears in many DP problems.

Problem 4: The 0/1 Knapsack

You have a bag that can carry a maximum weight, and items that each have a weight and a value. Each item can be taken at most once (that’s the “0/1”). What is the highest total value you can carry?

  • State: dp[i][w] = best value using only the first i items with a weight limit of w.
  • Transition: either skip item i (dp[i-1][w]) or, if it fits, take it (dp[i-1][w - weight] + value). Choose the bigger one.
  • Base case: with 0 items, the value is 0.
  • Answer: dp[n][capacity].
function knapsack(weights, values, capacity) {
  const n = weights.length;
  const dp = Array.from({ length: n + 1 }, () => new Array(capacity + 1).fill(0));
  for (let i = 1; i <= n; i++) {
    for (let w = 0; w <= capacity; w++) {
      dp[i][w] = dp[i - 1][w]; // skip item i
      if (weights[i - 1] <= w) {
        dp[i][w] = Math.max(dp[i][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]); // take it
      }
    }
  }
  return dp[n][capacity];
}

console.log(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7)); // 9  (weights 3 + 4, values 4 + 5)

The table has (n + 1) × (capacity + 1) cells and each takes O(1) work, so the time is O(n × capacity). Knapsack-style thinking is used for budgets, resource allocation and choosing which tasks fit into a time limit.

Problem 5: Longest Common Subsequence

A subsequence keeps characters in order but may skip some: “ACE” is a subsequence of “ABCDE”. The longest common subsequence (LCS) of two strings is the longest string that is a subsequence of both. It is the idea behind diff tools and Git, which show what changed between two files, and it is used to compare DNA sequences.

  • State: dp[i][j] = LCS length of the first i characters of a and the first j characters of b.
  • Transition: if the characters match, dp[i][j] = dp[i-1][j-1] + 1; otherwise max(dp[i-1][j], dp[i][j-1]).
  • Base cases: an empty string has LCS 0 with anything.

After filling the table, we walk back from the bottom-right corner to rebuild the actual subsequence:

function lcs(a, b) {
  const dp = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      dp[i][j] = a[i - 1] === b[j - 1]
        ? dp[i - 1][j - 1] + 1
        : Math.max(dp[i - 1][j], dp[i][j - 1]);
    }
  }
  // Walk back to build the subsequence itself
  let i = a.length, j = b.length, out = "";
  while (i > 0 && j > 0) {
    if (a[i - 1] === b[j - 1]) { out = a[i - 1] + out; i--; j--; }
    else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
    else j--;
  }
  return out;
}

console.log(lcs("ABCBDAB", "BDCABA")); // BCBA (length 4)

There can be more than one LCS of the same length (“BDAB” also works here); this code returns one of them.

Problem 6: Paths in a Grid

A robot starts at the top-left corner of a grid and can only move right or down. How many different paths lead to the bottom-right corner?

Every cell can be reached only from the cell above it or the cell to its left, so the number of paths to a cell is the sum of those two. The first row and first column have exactly one path each.

function uniquePaths(rows, cols) {
  const dp = Array.from({ length: rows }, () => new Array(cols).fill(1));
  for (let r = 1; r < rows; r++)
    for (let c = 1; c < cols; c++) dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
  return dp[rows - 1][cols - 1];
}

console.log(uniquePaths(3, 7)); // 28

Grid DP is used for map routing, image processing (for example, “seam carving” to resize images), and games.

Common Mistakes

  • Unclear state: if you can’t say in one sentence what dp[i] means, the transition will be wrong. Write the meaning down first.
  • Wrong base cases: an off-by-one in dp[0] or the first row breaks every value built on top of it. Check them by hand with a tiny input.
  • Wrong fill order: a cell must only use cells that are already filled.
  • Reaching for greedy: “always pick the biggest” feels right but, as coin change showed, can miss the best answer. When in doubt, test greedy against DP on small inputs.

Where Dynamic Programming Is Used

  • Text and code: spell checkers (edit distance), diff and version control (LCS).
  • Routes and networks: shortest-path algorithms such as Bellman-Ford and Floyd-Warshall.
  • Finance and planning: budgeting and portfolio problems (knapsack), scheduling.
  • Biology: DNA and protein sequence alignment.
  • Machine learning and speech recognition: the Viterbi algorithm.

Conclusion:

Dynamic programming solves a problem by solving each smaller sub-problem once and reusing its answer. Use it when sub-problems overlap and the best answer is built from the best answers of smaller parts. Write it top-down with memoization or bottom-up with tabulation, and follow the recipe: define the state, find the transition, set the base cases, choose the fill order, and pick the answer. Start with the classics in this lesson, and the same patterns will appear again and again in new problems.

In the next DSA lesson we will learn the two pointers and sliding window techniques, which solve many array and string problems in a single pass.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume