Consider there is a String S of size k+1 from c1…ck+1
Hash(H1) over k characters(c1..ck) could be computed as follows:
H1= c1*a^k-1 + c2*a^k-2+c3*a^k-3+…+ck*a^
where a is a constant
and c1…ck are input characters.
Lets assume you want to calculate the hash(H2) over same size window k over characters(c2..ck+1) could be computed from similar logic above as follows:
H2 = c2*a^k-1+c3*a^k-2+…+ck+1*
where a is a constant
and c2..ck+1 are input characters.
Now, if we look carefully, H2 = [H1*a] + [ck+1*a^0(i.e. last term of this window)] - [c1*a^k-1(i.e. first term of H1)]
So, in effect, whenever we are calculating rolling hash, we don't have to fully compute the hash. We can leverage the previously calculated hash and then it involved multiplying by a, subtracting the first term of last hash and adding the last character of this next window.
Similarly, whenever you compute rolling hash functions where either you shift the window right or left doesn't involve computing the whole hash function, but requires either multiplication or division by constant and subtraction/addition of last/first term.
Read full article from (1) How does the Rolling Hash function used in Rabin Karp algorithm work? - Quora
No comments:
Post a Comment