1. 2D table row
Extra row and column represent empty prefixes.
Array(text2.length + 1).fill(0)Typorithm · medium
Step 1 of 8 · intro card
Dynamic Programming
LCS uses a 2D table where each cell answers the best subsequence length for two prefixes.
Matching characters extend the diagonal result.
Different characters choose the better prefix after skipping one side.
The empty-prefix row and column make boundaries simple.
State: LCS length of prefixes i and j.
Match: diagonal + 1.
Mismatch: max(top, left).
Time O(m*n).
function longestCommonSubsequence(text1, text2) {
const dp = Array.from({ length: text1.length + 1 }, () =>
Array(text2.length + 1).fill(0),
);
for (let i = 1; i <= text1.length; i++) {
for (let j = 1; j <= text2.length; j++) {
if (text1[i - 1] === text2[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[text1.length][text2.length];
}Connect each part of the code to the concept before you type.
Extra row and column represent empty prefixes.
Array(text2.length + 1).fill(0)Each cell compares two prefixes.
for (let i = 1; i <= text1.length; i++)A match extends the diagonal subproblem.
dp[i][j] = dp[i - 1][j - 1] + 1When chars differ, skip one char from either string.
dp[i][j] = Math.max(dp[i - 1][j], dp[i][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