Skip to the content

Lesson 147 of 296

Dynamic programming: 2D, knapsack, LIS, LCS

What you will learn

  • DP on grids
  • Unique Paths
  • 0/1 Knapsack
  • Longest Increasing Subsequence
  • Longest Common Subsequence
  • Edit Distance
On this page

2D states

When a problem has two changing inputs (two positions in a grid, two strings, items and capacity), the state needs two indexes: dp[i][j].

Unique Paths

Problem (LeetCode 62): a robot in the top-left of an m × n grid can only move right or down. How many paths to the bottom-right?

State: dp[r][c] = number of paths to cell (r, c).
Transition: you arrive from above or from the left: dp[r][c] = dp[r-1][c] + dp[r][c-1].
Base: the first row and first column have exactly 1 path each.

Only the previous row is needed, so one array is enough:

TypeScript
function uniquePaths(m: number, n: number): number {
  const row = new Array<number>(n).fill(1);
  for (let r = 1; r < m; r++) {
    for (let c = 1; c < n; c++) {
      row[c] = row[c]! + row[c - 1]!;
    }
  }
  return row[n - 1]!;
}

Before the update, row[c] holds the value from the row above; row[c - 1] already holds the left value in the current row. O(m × n) time, O(n) space.

0/1 Knapsack

Problem: items each have a weight and a value. A bag holds at most capacity weight. Each item can be taken at most once. Maximum total value?

State: dp[w] = best value with total weight at most w, using the items considered so far.
Transition for each item: dp[w] = max(dp[w], dp[w - weight] + value).

TypeScript
function knapsack(weights: number[], values: number[], capacity: number): number {
  const dp = new Array<number>(capacity + 1).fill(0);
  for (let i = 0; i < weights.length; i++) {
    const weight = weights[i]!;
    const value = values[i]!;
    for (let w = capacity; w >= weight; w--) {
      dp[w] = Math.max(dp[w]!, dp[w - weight]! + value);
    }
  }
  return dp[capacity]!;
}

The loop goes backwards over w. Going forwards would let the same item be added twice in one round (that would be the unbounded knapsack, like Coin Change). O(items × capacity).

Many problems are knapsack in disguise: "Partition Equal Subset Sum" (LeetCode 416) asks whether some items sum to exactly half the total.

Longest Increasing Subsequence

Problem (LeetCode 300): the length of the longest strictly increasing subsequence (items in order, not necessarily next to each other).
[10, 9, 2, 5, 3, 7, 101, 18] → 4 ([2, 3, 7, 101]).

O(n²) DP: dp[i] = length of the longest increasing subsequence ending at i. For each earlier j with a smaller value, extend it.

TypeScript
function lengthOfLISQuadratic(nums: number[]): number {
  const dp = new Array<number>(nums.length).fill(1);
  let best = 0;
  for (let i = 0; i < nums.length; i++) {
    for (let j = 0; j < i; j++) {
      if (nums[j]! < nums[i]!) dp[i] = Math.max(dp[i]!, dp[j]! + 1);
    }
    best = Math.max(best, dp[i]!);
  }
  return best;
}

O(n log n) with binary search: keep tails, where tails[k] is the smallest possible ending value of an increasing subsequence of length k + 1. For each number, find the first tail that is >= it (lower bound, Lesson 131) and replace it, or append if it is bigger than all.

TypeScript
function lengthOfLIS(nums: number[]): number {
  const tails: number[] = [];
  for (const num of nums) {
    let low = 0;
    let high = tails.length;
    while (low < high) {
      const mid = Math.floor((low + high) / 2);
      if (tails[mid]! < num) low = mid + 1;
      else high = mid;
    }
    tails[low] = num;
  }
  return tails.length;
}

tails is not itself a valid subsequence, but its length is the answer. Explain the O(n²) version first; offer the faster one.

Longest Common Subsequence

Problem (LeetCode 1143): the length of the longest subsequence present in both strings.
"abcde" and "ace" → 3 ("ace").

State: dp[i][j] = LCS length of the first i characters of a and the first j characters of b.
Transition:

  • If a[i-1] === b[j-1]: dp[i][j] = dp[i-1][j-1] + 1 (use the matching character).
  • Otherwise: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) (drop a character from one string).
TypeScript
function longestCommonSubsequence(a: string, b: string): number {
  const dp: number[][] = Array.from({ length: a.length + 1 }, () =>
    new Array<number>(b.length + 1).fill(0)
  );
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      if (a[i - 1] === b[j - 1]) {
        dp[i]![j] = dp[i - 1]![j - 1]! + 1;
      } else {
        dp[i]![j] = Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!);
      }
    }
  }
  return dp[a.length]![b.length]!;
}

The extra row and column of zeros represent empty prefixes, which removes special cases. O(m × n) time and space (reducible to O(min(m, n)) with two rows). Real use: the diff in Git (Lesson 93) is based on this idea.

Edit Distance

Problem (LeetCode 72): the minimum number of insertions, deletions and replacements to turn one word into another.
"horse" → "ros" needs 3.

TypeScript
function minDistance(a: string, b: string): number {
  const dp: number[][] = Array.from({ length: a.length + 1 }, (_, i) =>
    Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))
  );
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      if (a[i - 1] === b[j - 1]) {
        dp[i]![j] = dp[i - 1]![j - 1]!;
      } else {
        dp[i]![j] = 1 + Math.min(dp[i - 1]![j]!, dp[i]![j - 1]!, dp[i - 1]![j - 1]!);
      }
    }
  }
  return dp[a.length]![b.length]!;
}

The three options are delete (from above), insert (from the left) and replace (diagonal). Used in spell checkers and fuzzy search.

How to say it in an interview

"With two changing inputs the state becomes two-dimensional. Unique Paths adds paths from above and from the left and can use a single row. 0/1 knapsack loops capacity backwards so each item is used once. For LIS I explain the O(n squared) ending-at-i DP, then the O(n log n) tails array with binary search. LCS and edit distance fill a table over prefixes with an extra empty row and column, matching characters on the diagonal, for O(m times n)."

Key words

WordMeaning
SubsequenceItems in order, not necessarily adjacent
KnapsackChoosing items under a weight limit to maximise value
0/1 vs unboundedEach item once / items reusable
LISLongest increasing subsequence
LCSLongest common subsequence
Edit distanceMinimum edits to turn one string into another

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.