Substring Search using Rabin Karp

This program searches substring using Rabin Karp algorithm.

Problem Statement

Write a Java program to search "abc" in "abdabcbabc".

Source Code

1 public class RabinKarpSearch {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Rabin Karp Search");
4 String txt="abdabcbabc", pat="abc";
5 int d=256,q=101;
6 int m=pat.length(), n=txt.length();
7 int p=0,t=0,h=1;
8 for(int i=0;i<m-1;i++) h=(h*d)%q;
9 for(int i=0;i<m;i++){
10 p=(d*p+pat.charAt(i))%q;
11 t=(d*t+txt.charAt(i))%q;
12 }
13 for(int i=0;i<=n-m;i++){
14 if(p==t){
15 if(txt.substring(i,i+m).equals(pat))
16 System.out.println("Found at index "+i);
17 }
18 if(i<n-m){
19 t=(d*(t-txt.charAt(i)*h)+txt.charAt(i+m))%q;
20 if(t<0) t+=q;
21 }
22 }
23 }
24 }

Program Output

Eduinq Rabin Karp Search
Found at index 2
Found at index 7

Explanation

A rolling hash is computed for both the pattern and each window of the text, and matching hash values trigger a direct string comparison to confirm the match, demonstrating the Rabin-Karp substring search algorithm.

Quick Links to Explore