I am trying to solve this problem using rabin-karp maching algorithm.
My hash function is
ll hash = 0;
ll P = 3; // only 3 characters are considered here 'a' ,'b', 'c';
ll MOD = 1e9+7;
string s; // hash of this string is calculated
for(int i=0; i<s.size();i++)
{
hash = (hash + (pow(P,i)*(s[i]-'a'+1))%MOD)%MOD;
}
Is there any better way to calculate the hash function to avoid conflict?
I tried to change (s[i] — 'a' + 1) by s[i]. Still getting conflict.
Thanks in Advance.
You most likely encountered the Birthday Paradox.
To fix this, either maintain two hashes with different
P
andMOD
, or calculate one hash with a large enoughMOD
(watch out for overflow!).Thanks for quick reply.
I changed the MOD value from 1e9+7 to 1e10+7 and using P = 29. My solution is accepted. 36981980
But, Maintaining two hashes will be a better.
You can use values 54059 and 257 as two seeds for two hashes and 1e9+7 as MOD in both hash functions. This gets you through most of the cases.
i tried it with 2 hashes. i think i am still getting collision. can someone help me why?