1. Home
  2. Explore
  3. Computer Science
  4. Dynamic Programming Course Intro

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Dynamic Programming Course Intro

Dynamic Programming: Comprehensive Study Notes

🧠 Introduction to Dynamic Programming

Dynamic programming (DP) is a powerful algorithmic technique for solving problems that exhibit overlapping subproblems and optimal substructure. Many students find DP intimidating, but it becomes intuitive when approached gradually.

Key insight: DP is applicable when:

  • A large problem can be broken down into smaller instances of the same problem

  • These smaller instances overlap (the same subproblem appears multiple times)

  • Solutions to subproblems can be reused rather than recomputed

Common DP problems include:

  • Fibonacci numbers

  • Counting paths in a grid

  • Coin change (minimum coins)

  • String construction from substrings

The course covers two main DP strategies:

  1. Memoization (top-down, recursive with caching)

  2. Tabulation (bottom-up, iterative table filling)


🔍 Part 1: Memoization

🧮 Understanding Recursion and Complexity

Before diving into DP, it's essential to analyze recursive functions using call trees. The height of the tree determines the recursion depth (and space complexity), while the branching factor determines how many nodes exist at each level.

Example: Simple recursive functions

function foo(n) {
  if (n <= 1) return; // base case
  foo(n - 1);
}
  • Time complexity: O(n)O(n)O(n) – one recursive call per level, height = n

  • Space complexity: O(n)O(n)O(n) – stack depth = n

function bar(n) {
  if (n <= 1) return;
  bar(n - 2);
}
  • Time complexity: O(n/2)=O(n)O(n/2) = O(n)O(n/2)=O(n) – still linear, constant factor removed

  • Space complexity: O(n)O(n)O(n) – height ~ n/2, simplifies to O(n)O(n)O(n)

function dib(n) {
  if (n <= 1) return;
  dib(n - 1);
  dib(n - 1);
}
  • Branching factor = 2, height = n → 2n2^n2n nodes

  • Time complexity: O(2n)O(2^n)O(2n)

  • Space complexity: O(n)O(n)O(n) – maximum stack depth = height = n

function lib(n) {
  if (n <= 1) return;
  lib(n - 2);
  lib(n - 2);
}
  • Branching factor = 2, height = n/2 → 2n/2=O(2n)2^{n/2} = O(2^n)2n/2=O(2n)

  • Space complexity: O(n/2)=O(n)O(n/2) = O(n)O(n/2)=O(n)

Key rule: For a recursive tree with branching factor bbb and height hhh, the time complexity is approximately bhb^hbh. The space complexity from the call stack is O(h)O(h)O(h).


🌀 The Fibonacci Problem

Problem: Write a function fib(n) that returns the nnnth Fibonacci number. The sequence: F1=1,F2=1F_1 = 1, F_2 = 1F1​=1,F2​=1, and Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}Fn​=Fn−1​+Fn−2​.

Brute-force recursive solution:

function fib(n) {
  if (n <= 2) return 1;
  return fib(n - 1) + fib(n - 2);
}

Why it's slow: The call tree for fib(7) reveals massive overlap:

  • Many identical subtrees (e.g., fib(3) appears multiple times)

  • The tree has height nnn and branching factor 2, giving O(2n)O(2^n)O(2n) time complexity

Visualizing overlapping subproblems:

The tree for fib(7) shows:

  • fib(5) appears multiple times

  • fib(4) appears multiple times

  • etc.

Since Fibonacci numbers are deterministic, recalculating them is wasteful.

Optimization via Memoization:

Use a JavaScript object (hash map) to store results. Keys = function arguments (n), values = return values.

function fib(n, memo = {}) {
  if (n in memo) return memo[n];
  if (n <= 2) return 1;
  memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
  return memo[n];
}

How it works:

  • Each unique n is calculated once

  • Subsequent calls look up the cached value

  • The tree becomes a linear chain: each n forks into n-1 and n-2, but n-2 is already cached from the n-1 branch

Complexity after memoization:

  • Time: O(n)O(n)O(n) – each distinct n computed once

  • Space: O(n)O(n)O(n) – memo object and stack depth


🌐 Grid Traveler Problem

Problem: Count the number of ways to travel from the top-left to bottom-right of an m×nm \times nm×n grid. Only moves allowed: down or right.

Key insight: When you move down, the grid shrinks to (m−1)×n(m-1) \times n(m−1)×n. When you move right, it becomes m×(n−1)m \times (n-1)m×(n−1). This yields the recurrence:

gridTraveler(m,n)=gridTraveler(m−1,n)+gridTraveler(m,n−1)\text{gridTraveler}(m,n) = \text{gridTraveler}(m-1,n) + \text{gridTraveler}(m,n-1)gridTraveler(m,n)=gridTraveler(m−1,n)+gridTraveler(m,n−1)

Base cases:

  • m=1,n=1m = 1, n = 1m=1,n=1 → 1 way (already at goal)

  • m=0m = 0m=0 or n=0n = 0n=0 → 0 ways (invalid grid)

Brute-force tree:

  • Height = m+nm + nm+n (since each step reduces one dimension)

  • Branching factor = 2 (down or right)

  • Time complexity: O(2m+n)O(2^{m+n})O(2m+n), space: O(m+n)O(m+n)O(m+n)

Memoization approach:

function gridTraveler(m, n, memo = {}) {
  const key = m + ',' + n;
  if (key in memo) return memo[key];
  if (m === 1 && n === 1) return 1;
  if (m === 0 || n === 0) return 0;
  memo[key] = gridTraveler(m - 1, n, memo) + gridTraveler(m, n - 1, memo);
  return memo[key];
}

Important: Use a comma separator in keys to avoid collisions (e.g., 42,3 vs. 4,23 would otherwise produce same key 423).

Complexity after memoization:

  • Time: O(m⋅n)O(m \cdot n)O(m⋅n) – at most m×nm \times nm×n unique subproblems

  • Space: O(m+n)O(m+n)O(m+n) – stack depth + memo object


📝 Memoization Recipe

  1. Make it work (brute force):

    • Visualize the problem as a tree

    • Nodes = function arguments (changeable parameters)

    • Edges = reduce problem size

    • Leaves = base cases (trivially small inputs)

    • Implement recursively, return values that combine sub-solutions

  2. Make it efficient (memoization):

    • Add a memo object (default empty for top-level call)

    • Share the memo across recursive calls (pass as argument)

    • Check memo first: if current arguments exist as key, return stored value

    • Store before returning: save computed result into memo using the arguments as key

    • Do not pre-check child calls; let them memoize themselves


🎯 Target Sum Problems (canSum, howSum, bestSum)

These problems share a common framework: given a target sum and an array of numbers, determine if/how/best to sum to target using numbers (unlimited usage).

canSum (decision problem)

Return true if target sum can be generated, else false.

Recursive structure:

  • For each number in array, subtract from target → remainder

  • If remainder < 0, return false

  • If remainder == 0, return true

  • Otherwise, recursively check if remainder can be made

Brute-force tree:

  • Height = mmm (target sum)

  • Branching factor = nnn (array length)

  • Time: O(nm)O(n^m)O(nm), Space: O(m)O(m)O(m)

Memoized version:

function canSum(targetSum, numbers, memo = {}) {
  if (targetSum in memo) return memo[targetSum];
  if (targetSum === 0) return true;
  if (targetSum < 0) return false;
  for (let num of numbers) {
    const remainder = targetSum - num;
    if (canSum(remainder, numbers, memo)) {
      memo[targetSum] = true;
      return true;
    }
  }
  memo[targetSum] = false;
  return false;
}

Complexity after memoization:

  • Time: O(m⋅n)O(m \cdot n)O(m⋅n) – at most mmm unique target sums, each iterates over nnn numbers

  • Space: O(m)O(m)O(m) – stack depth + memo

howSum (combinatorics problem)

Return one array of numbers that sums to target, or null if impossible.

Recursive base case: targetSum == 0 → return [] (empty array as the combination for zero).

Logic:

  • For each number, compute remainder

  • Recursively call howSum on remainder

  • If result is not null, copy that array and add the current number to it, then return that new array immediately (any valid combination works)

Memoization: targetSum as key, value = array (combination) or null.

Complexity after memoization:

  • Time: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) – each of mmm target sums requires looping over nnn numbers, and copying array of length up to mmm is O(m)O(m)O(m)

  • Space: O(m2)O(m^2)O(m2) – memo stores up to mmm keys, each value array up to length mmm

bestSum (optimization problem)

Return the shortest array that sums to target, or null.

Recursive strategy:

  • Explore all branches (cannot early return)

  • Keep track of the shortest combination found so far

  • At each node, compare the newly formed combination with current shortest; replace if shorter

Memoization: same key structure, but instead of storing any combination, store the shortest one for each target sum.

Implementation details:

  • Use shortestCombination variable initialized to null

  • When a combination is found, compare length with current shortest (skip if shortest is null)

  • Only replace if new combination is shorter

Complexity after memoization:

  • Time: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) – same reasoning as howSum

  • Space: O(m2)O(m^2)O(m2) – memo storage


🔤 String Construction Problems (canConstruct, countConstruct, allConstruct)

These problems involve constructing a target string by concatenating words from a word bank. Unlimited usage allowed.

canConstruct (decision problem)

Return true if target can be formed, else false.

Recursive structure:

  • Iterate through word bank

  • If a word is a prefix of the target string, remove it and recurse on the suffix

  • Base cases:

    • Empty string → true (no words needed)

    • No matching prefix → false

Tree analysis:

  • Height = mmm (target length)

  • Branching factor = nnn (number of words)

  • Time: O(nm⋅m)O(n^m \cdot m)O(nm⋅m) – each node may check prefix match (slice of length up to mmm)

  • Space: O(m2)O(m^2)O(m2) – stack depth and string creation

Memoization: key = target string (since word bank unchanged).

function canConstruct(target, wordBank, memo = {}) {
  if (target in memo) return memo[target];
  if (target === '') return true;
  for (let word of wordBank) {
    if (target.indexOf(word) === 0) { // word is prefix
      const suffix = target.slice(word.length);
      if (canConstruct(suffix, wordBank, memo)) {
        memo[target] = true;
        return true;
      }
    }
  }
  memo[target] = false;
  return false;
}

Complexity after memoization:

  • Time: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) – mmm unique target keys, each iterates nnn words, and suffix slicing costs O(m)O(m)O(m)

  • Space: O(m2)O(m^2)O(m2) – memo stores up to mmm strings, each up to length mmm

countConstruct (counting problem)

Return the number of ways to construct the target.

Recursive base: empty string → return 1 (one way: use no words).

Logic: Sum the results from all valid branches (prefix matches). No early termination.

Memoization: key = target, value = number of ways.

function countConstruct(target, wordBank, memo = {}) {
  if (target in memo) return memo[target];
  if (target === '') return 1;
  let totalCount = 0;
  for (let word of wordBank) {
    if (target.indexOf(word) === 0) {
      const suffix = target.slice(word.length);
      totalCount += countConstruct(suffix, wordBank, memo);
    }
  }
  memo[target] = totalCount;
  return totalCount;
}

Complexity after memoization: Same as canConstruct: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) time, O(m2)O(m^2)O(m2) space.

allConstruct (enumerate all solutions)

Return a 2D array containing all ways to construct the target. Each inner array is one combination of words.

Base cases:

  • Empty string → return [[]] (one way: empty combination)

  • No possible construction → return [] (empty array, meaning zero ways)

Recursive logic:

  • For each matching prefix word, recursively get all ways to build the suffix

  • For each way, prepend the current word to that way (add word to front of the inner array)

  • Combine results from all branches (concatenate the 2D arrays)

Important: This problem inherently requires full exploration; the number of solutions can be exponential. Memoization helps for repeated subproblems but does not reduce the size of the output.

Memoization: key = target, value = 2D array of all ways.

function allConstruct(target, wordBank, memo = {}) {
  if (target in memo) return memo[target];
  if (target === '') return [[]];
  const result = [];
  for (let word of wordBank) {
    if (target.indexOf(word) === 0) {
      const suffix = target.slice(word.length);
      const suffixWays = allConstruct(suffix, wordBank, memo);
      const targetWays = suffixWays.map(way => [word, ...way]);
      result.push(...targetWays);
    }
  }
  memo[target] = result;
  return result;
}

Complexity:

  • Time: O(nm)O(n^m)O(nm) – exponential due to the number of possible solutions

  • Space: Exponential – the memo and output may contain O(nm)O(n^m)O(nm) combinations, each of size O(m)O(m)O(m)


🏗️ Part 2: Tabulation

Tabulation is an iterative, bottom-up DP strategy. Instead of recursion + memo, we build a table (array) and fill it from smallest subproblem to largest.

📋 Tabulation Recipe

  1. Visualize the problem as a table.

    • Size of table should be based on the inputs that change (e.g., target sum, target length).

    • Often need +1 to handle zero-indexing and include the final state.

  2. Initialize the table with default values.

    • Use the return type to choose initial values:

      • Counting problems → 0

      • Boolean problems → false (or null for "no combination")

      • Array problems → empty array (for "no ways") or null

  3. Seed the trivial base case.

    • For index 0 (or the smallest input), set the correct answer (e.g., table[0] = true, table[0] = 1, table[0] = [[]], etc.).

  4. Iterate through the table (usually left to right).

    • At each position, if the current value indicates the subproblem is solvable, use it to fill future positions based on problem rules (e.g., adding numbers, taking prefixes).

    • Update future positions by adding or copying the current value.

  5. Return the value at the final index (corresponding to the original problem).


🌀 Fibonacci with Tabulation

Goal: Compute FnF_nFn​ where F0=0F_0 = 0F0​=0, F1=1F_1 = 1F1​=1, Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}Fn​=Fn−1​+Fn−2​.

Table size: n+1n+1n+1 (indices 0 through n).

Initialize: All zeros, then table[1] = 1.

Iteration: For each iii from 0 to nnn:

  • Add table[i] to table[i+1] and table[i+2] (if within bounds).

Final: table[n] is the answer.

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

Complexity: O(n)O(n)O(n) time, O(n)O(n)O(n) space.


🌐 Grid Traveler with Tabulation

Goal: Count ways to travel m×nm \times nm×n grid.

Table: 2D array of size (m+1)×(n+1)(m+1) \times (n+1)(m+1)×(n+1), filled with 0.

Seed: table[1][1] = 1.

Iteration: For each cell (i,j):

  • Add current value to table[i+1][j] (down neighbor) and table[i][j+1] (right neighbor), if within bounds.

Final: table[m][n].

function gridTraveler(m, n) {
  const table = new Array(m + 1).fill().map(() => new Array(n + 1).fill(0));
  table[1][1] = 1;
  for (let i = 0; i <= m; i++) {
    for (let j = 0; j <= n; j++) {
      const current = table[i][j];
      if (current === 0) continue;
      if (i + 1 <= m) table[i + 1][j] += current;
      if (j + 1 <= n) table[i][j + 1] += current;
    }
  }
  return table[m][n];
}

Complexity: O(m⋅n)O(m \cdot n)O(m⋅n) time and space.


🎯 Target Sum: canSum with Tabulation

Goal: Boolean if target sum can be formed from numbers.

Table: Size target + 1, filled with false.
Seed: table[0] = true.

Iteration: For each iii from 0 to target:

  • If table[i] is true, then for each num in numbers:

    • If i + num <= target, set table[i + num] = true.

Final: table[target].

function canSum(target, numbers) {
  const table = new Array(target + 1).fill(false);
  table[0] = true;
  for (let i = 0; i <= target; i++) {
    if (table[i]) {
      for (let num of numbers) {
        if (i + num <= target) table[i + num] = true;
      }
    }
  }
  return table[target];
}

Complexity: O(m⋅n)O(m \cdot n)O(m⋅n) time, O(m)O(m)O(m) space.


🎯 Target Sum: howSum with Tabulation

Goal: Return one combination (array) that sums to target, or null.

Table: Size target + 1, filled with null.
Seed: table[0] = [] (empty array represents combination for zero).

Iteration: For each iii from 0 to target:

  • If table[i] !== null, then for each num in numbers:

    • If i + num <= target:

      • Create a new array: [...table[i], num]

      • If table[i + num] is null, assign it this new array (first found).

Final: table[target] (could be null or array).

function howSum(target, numbers) {
  const table = new Array(target + 1).fill(null);
  table[0] = [];
  for (let i = 0; i <= target; i++) {
    if (table[i] !== null) {
      for (let num of numbers) {
        if (i + num <= target) {
          const combination = [...table[i], num];
          if (table[i + num] === null) table[i + num] = combination;
        }
      }
    }
  }
  return table[target];
}

Complexity: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) time (copying arrays of length up to mmm), O(m2)O(m^2)O(m2) space.


🎯 Target Sum: bestSum with Tabulation

Goal: Return the shortest combination.

Table: Same as howSum, but when updating, compare lengths and keep the shorter one.

function bestSum(target, numbers) {
  const table = new Array(target + 1).fill(null);
  table[0] = [];
  for (let i = 0; i <= target; i++) {
    if (table[i] !== null) {
      for (let num of numbers) {
        if (i + num <= target) {
          const combination = [...table[i], num];
          if (table[i + num] === null || combination.length < table[i + num].length) {
            table[i + num] = combination;
          }
        }
      }
    }
  }
  return table[target];
}

Complexity: Same as howSum: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) time, O(m2)O(m^2)O(m2) space.


🔤 String Problems with Tabulation

For string problems, the table indices correspond to prefixes of the target string. Index iii represents the substring from index 0 to iii (exclusive). This requires table size target.length + 1.

canConstruct Tabulation

Table: Boolean array of length target.length + 1, initialized false.
Seed: table[0] = true (empty string always constructible).

Iteration: For each iii from 0 to target length:

  • If table[i] is true, then for each word:

    • If the word matches the characters starting at position iii (i.e., target.slice(i, i + word.length) === word):

      • Set table[i + word.length] = true.

Final: table[target.length].

function canConstruct(target, wordBank) {
  const table = new Array(target.length + 1).fill(false);
  table[0] = true;
  for (let i = 0; i <= target.length; i++) {
    if (table[i]) {
      for (let word of wordBank) {
        if (target.slice(i, i + word.length) === word) {
          table[i + word.length] = true;
        }
      }
    }
  }
  return table[target.length];
}

Complexity: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) time (slice costs O(m)O(m)O(m)), O(m)O(m)O(m) space.

countConstruct Tabulation

Table: Number array of length target.length + 1, initialized 0.
Seed: table[0] = 1.

Iteration: Same as canConstruct, but instead of setting true, add table[i] to table[i + word.length].

function countConstruct(target, wordBank) {
  const table = new Array(target.length + 1).fill(0);
  table[0] = 1;
  for (let i = 0; i <= target.length; i++) {
    if (table[i] > 0) {
      for (let word of wordBank) {
        if (target.slice(i, i + word.length) === word) {
          table[i + word.length] += table[i];
        }
      }
    }
  }
  return table[target.length];
}

Complexity: O(m2⋅n)O(m^2 \cdot n)O(m2⋅n) time, O(m)O(m)O(m) space.

allConstruct Tabulation

Table: Array of arrays. Each position holds a 2D array containing all ways to construct the corresponding prefix.
Seed: table[0] = [[]] (one way: empty combination).
All other positions initialized as [] (empty array = zero ways).

Iteration: For each iii from 0 to target length:

  • If table[i] is non-empty (has at least one way), then for each word that matches starting at iii:

    • For each way in table[i], create a new way: [...way, word]

    • Push all these new ways into table[i + word.length].

Final: table[target.length].

function allConstruct(target, wordBank) {
  const table = new Array(target.length + 1).fill().map(() => []);
  table[0] = [[]];
  for (let i = 0; i <= target.length; i++) {
    for (let word of wordBank) {
      if (target.slice(i, i + word.length) === word) {
        const newCombinations = table[i].map(subArray => [...subArray, word]);
        table[i + word.length].push(...newCombinations);
      }
    }
  }
  return table[target.length];
}

Complexity: Inherently exponential – the table may hold O(nm)O(n^m)O(nm) combinations. Time and space are at least exponential.


💡 Final Advice

  • Always start by looking for overlapping subproblems – the hallmark of DP.

  • Identify the smallest trivial input (base case). For numbers, often 0 or 1; for strings, the empty string; for arrays, empty array.

  • Decide between memoization and tabulation:

    • Memoization: intuitive for problems with recursive structure; easy to implement once brute force is written.

    • Tabulation: often more efficient (no recursion overhead, avoids stack limits); good for problems where subproblem order is natural.

  • Draw the problem – visualize the tree or table before coding.

  • Use bold for key terms (e.g., overlapping subproblems, memoization, tabulation, prefix).

  • Use LaTeX for complexity: O(2n)O(2^n)O(2n), O(m⋅n)O(m \cdot n)O(m⋅n), etc.

With practice, DP becomes a systematic tool. The progression from canSum → howSum → bestSum and canConstruct → countConstruct → allConstruct shows how small changes in the question lead to variations in the DP solution. Master these patterns, and you will be well-prepared for algorithm interviews.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent