progress

~/problems / String hashing

Prefix hashes for O(1) substring comparison

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Implement class SubstringHasher, which preprocesses a string once so substrings can be compared without reading their characters:

  • SubstringHasher(s) builds the tables.
  • get(l, r) returns the polynomial hash of s[l:r] (0 <= l <= r <= len(s)), exactly as defined below.
  • same(i, j, length): is s[i:i+length] == s[j:j+length]? Both ranges fit; length may be 0.
h = SubstringHasher("abcabd")
h.same(0, 3, 2)    # True   ("ab" == "ab")
h.same(0, 3, 3)    # False  ("abc" != "abd")
h.get(0, 2) == h.get(3, 5)   # True

The hash reads characters as base-B = 131 digits modulo the prime M = 2**61 - 1, first character most significant; the empty string hashes to 0:

hash(t) = (ord(t[0]) * B**(k-1) + ord(t[1]) * B**(k-2) + ... + ord(t[k-1])) % M,   k = len(t)

The Python starter defines B and M. In C++ or Java, declare them, and beware that two values below 2**61 overflow 64 bits when multiplied: use __uint128_t in C++, or Math.multiplyHigh in Java (since 2**61 ≡ 1 (mod M), the high part is just added back in).

⭐ Bonus: a speed test with 100,000 calls on long substrings of a 200,000-character string earns a star if get and same are O(1): store prefix hashes h[i] (of s[:i]) and powers p[i] = B**i % M.

Show hint

h[i + 1] = (h[i] * B + ord(s[i])) % M, and s[l:r] hashes to (h[r] - h[l] * p[r - l]) % M.

Topic: String hashing / Rabin-Karp. Rolling polynomial hash for O(1) substring comparison.

0:00
Ctrl ' run · Ctrl ↵ submit
esc