1. Empty prefix cost
Converting empty to length k needs k inserts or deletes.
i === 0 ? j : j === 0 ? i : 0Typorithm · hard
Step 1 of 8 · intro card
Dynamic Programming
Edit Distance finds the minimum insert, delete, and replace operations between two strings.
Each cell compares two prefixes.
Equal characters carry over the diagonal.
Different characters add one operation to the best edit choice.
State: min edits between prefixes.
Base: empty prefix costs length.
Match: diagonal.
Mismatch: 1 + min(delete, insert, replace).
function minDistance(word1, word2) {
const dp = Array.from({ length: word1.length + 1 }, (_, i) =>
Array.from({ length: word2.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
);
for (let i = 1; i <= word1.length; i++) {
for (let j = 1; j <= word2.length; j++) {
if (word1[i - 1] === word2[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[word1.length][word2.length];
}Connect each part of the code to the concept before you type.
Converting empty to length k needs k inserts or deletes.
i === 0 ? j : j === 0 ? i : 0Equal chars cost nothing new.
dp[i][j] = dp[i - 1][j - 1]Try delete, insert, or replace.
1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputRows: ∅abc · columns: ∅ac
Follow temporary values, local state and supporting structures at this step.
↗ The 12-cell working table above is itself auxiliary memory. Input values are shown separately.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state