Input: txt = "THIS IS A TEST TEXT" pat = "TEST" Output: Pattern found at index 10 Input: txt = "AABAACAADAABAABA" pat = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12
The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.
Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings.
1) Pattern itself.
2) All the substrings of text of length m.
Pattern found at index 0 Pattern found at index 10
Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.