A help for people learning Hashing

Revision en3, by Luisito_0_1_0_1, 2025-11-14 22:35:12

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
}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English Luisito_0_1_0_1 2025-11-14 22:35:12 25 Tiny change: '\n}\n```\nSoYYYYYYYY GaYYYYYYYYYYYY' -> '\n}\n```\n'
en2 English Luisito_0_1_0_1 2025-11-14 22:33:41 27 Tiny change: '/b\n}\n```' -> '/b\n}\n```\nSoYYYYYYYY GaYYYYYYYYYYYY'
en1 English Luisito_0_1_0_1 2025-11-14 19:58:03 1640 Initial revision (published)