Worked example and algorithm walkthrough
Topic: Dynamic Programming · String DP
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"a": "abcjklp",
"b": "acjkp",
"mode": "substring"
}Execution steps
- Compute string DP cell
Computed output
3
JavaScript reference implementation
const solve = ({
a,b,mode
},s)=>{
let d=Array.from({
length:a.length+1
},()=>Array(b.length+1).fill(0)),best=0;
if(mode==="distinct")for(let i=0;
i<=a.length;
i++)d[i][0]=1;
if(mode==="wild"){
d[0][0]=1;
for(let j=1;
j<=b.length;
j++)d[0][j]=b[j-1]==="*"?d[0][j-1]:0
}
for(let i=1;
i<=a.length;
i++)for(let j=1;
j<=b.length;
j++){
let eq=a[i-1]===b[j-1];
if(mode==="distinct")d[i][j]=d[i-1][j]+(eq?d[i-1][j-1]:0);
else if(mode==="wild")d[i][j]=b[j-1]==="*"?Math.max(d[i-1][j],d[i][j-1]):eq||b[j-1]==="?"?d[i-1][j-1]:0;
else if(mode==="substring"){
d[i][j]=eq?1+d[i-1][j-1]:0;
best=Math.max(best,d[i][j])
}else d[i][j]=eq?1+d[i-1][j-1]:Math.max(d[i-1][j],d[i][j-1]);
s("Compute string DP cell",{
A:[...a],B:[...b],DP:d,Cell:[i,j]
})
}
let v=d[a.length][b.length];
if(mode==="wild")return !!v;
if(mode==="substring")return best;
if(mode==="length"||mode==="distinct")return v;
if(mode==="insert")return a.length-v;
if(mode==="convert")return a.length+b.length-2*v;
let i=a.length,j=b.length,o="";
while(i&&j){
if(a[i-1]===b[j-1]){
o=a[--i]+o;
j--
}else if(d[i-1][j]>=d[i][j-1]){
if(mode==="scs")o=a[i-1]+o;
i--
}else{
if(mode==="scs")o=b[j-1]+o;
j--
}
s("Backtrack table",{
DP:d,Output:[...o],Cell:[i,j]
})
}
return mode==="scs"?a.slice(0,i)+b.slice(0,j)+o:o
};