Sikau

Algorithms · Day 14 · about 45 min

DP classics: edit distance and knapsack

2-D tables for comparing strings and choosing under a budget.

Did you mean "thukpa"?

Search boxes forgive typos by measuring edit distance: the fewest insertions, deletions and substitutions to turn one word into another. And "pick the best items within a weight or budget" is the 0/1 knapsack problem. Both use 2-D DP tables.

Two tables

function editDistance(a, b) {
  const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...new Array(b.length).fill(0)]);
  for (let j = 0; j <= b.length; j++) dp[0][j] = j;
  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.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
  return dp[a.length][b.length];
}
console.log(editDistance("thupka", "thukpa"), editDistance("momo", "momos"), editDistance("", "tea"));

// 0/1 knapsack: best value within a capacity, each item at most once.
function knapsack(items, capacity) {
  const best = new Array(capacity + 1).fill(0);
  for (const { weight, value } of items)
    for (let c = capacity; c >= weight; c--)
      best[c] = Math.max(best[c], best[c - weight] + value);
  return best[capacity];
}
console.log(knapsack([{ weight: 3, value: 40 }, { weight: 4, value: 50 }, { weight: 2, value: 30 }], 6));

The rest of this lesson

  • Reading the edit-distance tableexplain
  • 0/1 knapsack in one dimensionexplain
  • Edit distancepredict
  • A small edit distancepredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of Algorithms