Hello! I made a C++ class called "HashingStr"; it can be useful for people who are learning about this topic. If you don't know what it is about, here's the following link: **https://cp-algorithms.com/string/string-hashing.html** There you will learn more about this algorithm. I hope it helps you ;)
WARNING: Using this for a problem can cause collisions, leading to incorrect answers. I recommend using it only when there is nothing else left to do. Always think about the best solution!
#include <bits/stdc++.h>
using namespace std;
class HashedStr{
private:
//The values of these three variables can be changed according to your preferences
const int md=1e9+7;
const int prim=31;
const char min_alphabet='a';
string str;
vector<int>pot;
vector<int>hash;
public:
HashedStr(string s){
str=s;
pot.push_back(1);
hash.push_back(0);
for(int i=1;i<=s.size();i++){
pot.push_back((pot[i-1]*prim)%md);
hash.push_back((hash[i-1]*prim+(s[i-1]-min_alphabet+1))%md);
}
}
int gethash(int l,int r){
l++;r++; //Delete this line for 1-indexed querys
int re=(hash[r]-hash[l-1]*pot[r-l+1])%md;
return re<0?re+md:re;
}
};
int32_t main(){
HashedStr s("ababababab");
cout<<s.gethash(0,1)<<endl; //ab
cout<<s.gethash(2,3)<<endl; //ab
cout<<s.gethash(0,3)<<endl; //abab
cout<<s.gethash(4,7)<<endl; //abab
cout<<s.gethash(0,0)<<endl; //a
cout<<s.gethash(1,1)<<endl; //b
}








To substantially reduce the probability of collisions, something that hashes against two (or more) prime mods can be used.
Many string problems have an alternate hashing solution, so I'd argue that it's good to be able to spot such a solution even if it isn't necessarily "intended." (The hashing solution is often just as easy if not easier to code as well.)
.
.
Try to solve Hash-Killer 3
it's true hash