Rolling hash. O(1) time to compute queue's hash

2015-05-18 13:52:39

Author: lipeng (2) (2)

The key idea of rolling hash is to generate hash of n+1 elements in O(1) time, by knowing hash of n elements.
Here is a great introduction for rolling hash from TopCoder:
https://www.topcoder.com/community/data-science/data-science-tutorials/introduction-to-string-searching-algorithms/

And here is an application for checking palindrome in a stream rolling hash from g4g:
http://www.geeksforgeeks.org/online-algorithm-for-checking-palindrome-in-a-stream/

They are great, and it supports the below changes:
"bcde" -> "abcde", by doing str = (str + h*str[i/2])%q;
"bcde" -> "bcdef", by doing str = (str*d + str[i+1])%q;
"bcde" -> "cdef", by doing str = (d*(str + q - str[(i+1)/2]*h)%q

During the calculation, we need to store the base^n, which we called MAGIC. Unfortunately, above articles don't mention this type of change:
"bcde" -> "cde".

Let's assume hash for "bcde" is: And our aim is to get below hash. To get this done is very easy: we just do hash("bcde") - MAGIC * hash('b').
Since the number of elements reduces from 4 to 3, how do we calculate the next MAGIC, which is The general problem is that how do we calculate from , with modular q. Having instantly learned some modular arithmetic knowledge, I got it that we can calculate it by multiplicative inverse.
For example,
We should computes m for if we know: How do we calculate: To be honest, I don't really know how to compute it. But good news is that we can use BigInteger to get it:
BigInteger.valueOf(11).modInverse(BigInteger.valueOf(97)). This is calculation takes O(log97) time, it is a constant.

Isn't it cool!! By help of BigInteger, we got m is 53.
Now, let (31 * 53) mod 97, we got 91.

Let's use calculate to verify It is 91 too! We are right!

Below is a queue application for rolling hash. Every time when we enQueue or deQueue, we can use O(1) time to finish the hash for the whole queue. Furthermore, we can quickly check if 2 Queues are the same.

package util;

import lombok.Getter;
import java.math.BigInteger;

/**
* Created by PLi on 6/4/2015.
*/
public class RollingHashQueue<E> {

/** base is the number of characters in input alphabet **/
private final int base = 31;

/** q is a prime number used for evaluating Rabin Karp's Rolling hash **/
private final int q = 103;

/** magic base^(n-1). n is the number of element the list has. **/
private int magic = 1;

@Getter
private int rollingHash;

private int magicModInverse;

public RollingHashQueue(){
magicModInverse = BigInteger.valueOf(base).modInverse(BigInteger.valueOf(q)).intValue();
}

/** enQueue, add element to queue tail **/
rollingHash = ((rollingHash * base) % q + e.hashCode()) % q;
magic = (magic * base) % q;
return true;
}

rollingHash = ((magic * e.hashCode()) % q + rollingHash ) % q;
magic = (magic * base) % q;
return true;
}

/** deQueue, remove element from queue head **/
public E removeFirst(){
if(list==null || list.size()==0){
return null;
}
magic = (magic * magicModInverse) % q;
rollingHash = (rollingHash - (magic * list.get(0).hashCode()) % q + q) % q;
E e = list.remove(0);
return e;
}

/** remove element from queue tail **/
public E removeLast(){
if(list==null || list.size()==0){
return null;
}
magic = (magic * magicModInverse) % q;
rollingHash = (((rollingHash - list.getLast().hashCode() + q) % q) * magicModInverse) % q;
E e = list.removeLast();
return e;
}

public int hashCode() {
return this.hashCode();
}

public boolean equals(RollingHashQueue<E> queue2){
if(queue2==null || this.rollingHash!=queue2.rollingHash || !this.list.equals(queue2.list)){
return false;
}
return true;
}

public E getFirst(){
return list.getFirst();
}

public E getLast(){
return list.getLast();
}

public E get(int i){
return list.get(i);
}

public String toString(){
return list.toString();
}

}

In the end, thank Victor Costan from MIT to inspire how to calculate the MAGIC!

• I think you didn't understand the aim of my code. Actually, my code is not for computing the largest palindrome. My code adds a function for queue. It can help queue be able to compute hashcode in O(1) time when enQueue or deQueue happens. You remember we wrote the code to monitor max/min value in queue? I think this can make queue much powerful :)

Written 2015-05-28 11:54:07 by lipeng
• interesting MAGIC number, however the hash computing can be simplified. check out my post: http://blueocean-penn.blogspot.com/2015/05/rabin-karp-algorithm.html

Written 2015-05-23 04:13:40 by junmin

Back