Lably
Skip to content

Rolling hash

  • 7 min read
  • 7 chapters

Related on Lably

Through Hash function, Moving average and Modular arithmetic

A few hash functions allow a rolling hash to be computed very quickly—the new hash value is rapidly calculated given only the old hash value, the old value removed from the window, and the new value added to the window—similar to the way a moving average function can be computed much more quickly than other low-pass filters; and similar to the way a Zobrist hash can be rapidly updated from the old hash value.

One of the main applications is the Rabin–Karp string search algorithm, which uses the rolling hash described below. Another popular application is the rsync program, which uses a checksum based on Mark Adler's adler-32 as its rolling hash. Low Bandwidth Network Filesystem (LBFS) uses a Rabin fingerprint as its rolling hash. FastCDC (Fast Content-Defined Chunking) uses a compute-efficient Gear fingerprint as its rolling hash.

At best, rolling hash values are pairwise independent or strongly universal. They cannot be 3-wise independent, for example.

Polynomial rolling hash

The Rabin–Karp string search algorithm is often explained using a rolling hash function that only uses multiplications and additions:

H=c1ak−1+c2ak−2+c3ak−3+...+cka0,

where a is a constant, and c1,...,ck are the input characters (but this function is not a Rabin fingerprint, see below).

In order to avoid manipulating huge H values, all math is done modulo n. The choice of a and n is critical to get good hashing; in particular, the modulus n is typically a prime number. See linear congruential generator for more discussion.

Removing and adding characters simply involves adding or subtracting the first or last term. Shifting all characters by one position to the left requires multiplying the entire sum H by a. Shifting all characters by one position to the right requires dividing the entire sum H by a. Note that in modulo arithmetic, a can be chosen to have a multiplicative inverse a−1 by which H can be multiplied to get the result of the division without actually performing a division.

Sign in to keep reading

6 more chapters are free with a Lably account.

More in Computing and communication