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 STUDIOLEARN BY DOING Predict. Execute. Understand. Follow the source code, inspect live state changes, and predict the next operation before revealing it.
1 / 4 Execution step
Prediction modePanel width Reference example · JavaScript
Inspect reference input {
"a": "ababa",
"b": "aba"
} Code Visuals
JavaScript reference implementation · highlighted trace statement
1 const solve = ({
2 a,b
3 },s)=>{
4 let base=31 ,mod=101 ,p=0 ,h=0 ,pow=1 ,o=[];
5 for (let i=0 ;
6 i<b.length;
7 i++){
8 p=(p*base+b.charCodeAt(i))%mod;
9 h=(h*base+a.charCodeAt(i))%mod;
10 if (i)pow=pow*base%mod
11 }
12 for (let i=0 ;
13 i+b.length<=a.length;
14 i++){
15 if (h===p&&a.slice(i,i+b.length)===b)o.push(i);
16 s("Compare rolling hashes; verify collisions",{
17 Array:[...a],Hashes:[h,p],Matches:o
18 },[i]);
19 if (i+b.length<a.length)h=((h-a.charCodeAt(i)*pow%mod+mod)*base+a.charCodeAt(i+b.length))%mod
20 }
21 return o
22 };
Execution canvas Active ChangedSTEP 1 Compare rolling hashes; verify collisions 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": "ababa",
"b": "aba"
} Execution steps 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.