Workspace Rabin Karp Search
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Rabin Karp Search visualizer

Learn Rabin Karp Search 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 / 4Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": "ababa",
  "b": "aba"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,b
},s)=>{
let base=31,mod=101,p=0,h=0,pow=1,o=[];
for(let i=0;
i<b.length;
i++){
p=(p*base+b.charCodeAt(i))%mod;
h=(h*base+a.charCodeAt(i))%mod;
if(i)pow=pow*base%mod
}
for(let i=0;
i+b.length<=a.length;
i++){
if(h===p&&a.slice(i,i+b.length)===b)o.push(i);
s("Compare rolling hashes; verify collisions",{
Array:[...a],Hashes:[h,p],Matches:o
},[i]);
if(i+b.length<a.length)h=((h-a.charCodeAt(i)*pow%mod+mod)*base+a.charCodeAt(i+b.length))%mod
}
return o
};

Execution canvas

Active Changed
STEP 1

Compare rolling hashes; verify collisions

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

Array5 items
Hashes2 items
Matches1 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": "ababa",
  "b": "aba"
}

Execution steps

  1. Compare rolling hashes; verify collisions

Computed output

[
  0,
  2
]
JavaScript reference implementation
const solve = ({
  a,b
},s)=>{
  let base=31,mod=101,p=0,h=0,pow=1,o=[];
  for(let i=0;
  i<b.length;
  i++){
    p=(p*base+b.charCodeAt(i))%mod;
    h=(h*base+a.charCodeAt(i))%mod;
    if(i)pow=pow*base%mod
  }
  for(let i=0;
  i+b.length<=a.length;
  i++){
    if(h===p&&a.slice(i,i+b.length)===b)o.push(i);
    s("Compare rolling hashes; verify collisions",{
      Array:[...a],Hashes:[h,p],Matches:o
    },[i]);
    if(i+b.length<a.length)h=((h-a.charCodeAt(i)*pow%mod+mod)*base+a.charCodeAt(i+b.length))%mod
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.