Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions RabinKarpAlgorithm/rabin_karp.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <bits/stdc++.h>
using namespace std;

#define ch 256

void search(char pattern[], char text[], int q)
{
int M = strlen(pattern);
int N = strlen(text);
int i, j;
int p = 0;
int t = 0;
int h = 1;

for (i = 0; i < M - 1; i++)
h = (h * ch) % q;

for (i = 0; i < M; i++)
{
p = (ch * p + pattern[i]) % q;
t = (ch * t + text[i]) % q;
}

// Here we slide the pattern over the string one by one.
for (i = 0; i <= N - M; i++)
{

// Checking if the hash values for each of these match. If they match, only then we move forward to check the entire pattern.
if (p == t)
{
bool flag = true;
// Checking for characters one by one
for (j = 0; j < M; j++)
{
if (text[i + j] != pattern[j])
{
flag = false;
break;
}
}
if (j == M)
cout << "Pattern found at index " << i << endl;
}
if (i < N - M)
{
t = (ch * (t - text[i] * h) + text[i + M]) % q;

// We might get negative value of t, so we need to convert it into a positive value.
if (t < 0)
t = (t + q);
}
}
}

int main()
{
char text[] = "KARTIK";
char pattern[] = "ART";
int q = 101;
search(pattern, text, q);
return 0;
}
9 changes: 9 additions & 0 deletions RabinKarpAlgorithm/rabin_karp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
## Rabin Karp Algorithm

This is the code for the Rabin Karp algorithm, which is used for pattern finding in a given string using a hash function. Unlike Naive string matching algorithm, it does not travel through every character in the initial phase rather it filters the characters that do not match and then performs the comparison

**Time complexity of this algorithm**
- Let the length of the string be m.
- Let the length of the pattern to be found be n.

The average and best-case running time of the Rabin-Karp algorithm is O(n+m), but its worst-case time is O(nm).