Workspace Kmp Pattern Matching
0d
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 STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 10Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": "abababa",
  "b": "aba"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
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
};

Execution canvas

Active Changed
STEP 1

Build prefix table

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Pattern3 items
LPS3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

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

  1. Build prefix table
  2. 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.