Back to questionsDSA Visualizers: 388 Coding Questions KMP Pattern Matching visualizer Learn KMP Pattern Matching with a step-by-step Strings visualizer, JavaScript source code and a worked example. Practice pattern matching.
INTERACTIVE EXECUTION STUDIOLEARN BY DOING Predict. Execute. Understand. Follow the source code, inspect live state changes, and predict the next operation before revealing it.
1 / 10 Execution step
Prediction modePanel width Reference example · JavaScript
Inspect reference input {
"a": "abababa",
"b": "aba"
} Code Visuals
JavaScript reference implementation · highlighted trace statement
1 const solve = ({
2 a,b
3 },s)=>{
4 let p=Array(b.length).fill(0 ),j=0 ,o=[];
5 for (let i=1 ;
6 i<b.length;
7 i++){
8 while (j&&b[i]!==b[j])j=p[j-1 ];
9 if (b[i]===b[j])j++;
10 p[i]=j;
11 s("Build prefix table",{
12 Pattern:[...b],LPS:p
13 },[i])
14 }
15 j=0 ;
16 for (let i=0 ;
17 i<a.length;
18 i++){
19 while (j&&a[i]!==b[j])j=p[j-1 ];
20 if (a[i]===b[j])j++;
21 if (j===b.length){
22 o.push(i-j+1 );
23 j=p[j-1 ]
24 }
25 s("Advance or fall back",{
26 Array:[...a],LPS:p,Matches:o
27 },[i])
28 }
29 return o
30 };
Execution canvas Active ChangedSTEP 1 Build prefix table Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.
Worked example and algorithm walkthrough Topic: Strings · Pattern matching
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": "abababa",
"b": "aba"
} Execution steps Build prefix table Advance or fall back Computed output [
0,
2,
4
] JavaScript reference implementation const solve = ({
a,b
},s)=>{
let p=Array(b.length).fill(0),j=0,o=[];
for(let i=1;
i<b.length;
i++){
while(j&&b[i]!==b[j])j=p[j-1];
if(b[i]===b[j])j++;
p[i]=j;
s("Build prefix table",{
Pattern:[...b],LPS:p
},[i])
}
j=0;
for(let i=0;
i<a.length;
i++){
while(j&&a[i]!==b[j])j=p[j-1];
if(a[i]===b[j])j++;
if(j===b.length){
o.push(i-j+1);
j=p[j-1]
}
s("Advance or fall back",{
Array:[...a],LPS:p,Matches:o
},[i])
}
return o
};Continue learning Practice related DSA questions in the same topic.