Learn / Advanced structures

String hashing

A polynomial hash turns a string into a number, and prefix hashes give the hash of any substring in O(1). Equal substrings have equal hashes; different ones almost always differ, so comparisons that took O(length) take O(1). The sheets this guide follows have no problems for this pattern, so the lesson explains the idea and when to use it.

How to recognise it

  • Comparing many substrings for equality.
  • Finding a repeated substring of a given length.
  • Pattern matching (Rabin-Karp) or palindrome checks with binary search.

Prefix hashes

h[0] = 0; h[i + 1] = h[i] × p + code(s[i])   (mod M)
pw[0] = 1; pw[i + 1] = pw[i] × p             (mod M)
hash(l, r) = (h[r + 1] - h[l] × pw[r - l + 1]) mod M

Common mistakes

  • Negative values after the subtraction: add M before taking the remainder.
  • Mapping 'a' to 0, which makes 'a' and 'aa' collide.

Problems

No problems listed for this pattern yet.

Check yourself

How is the hash of s[l..r] found from prefix hashes?

Why use a large prime modulus (or two)?

Does equal hash prove equal strings?