A2Z Lesson

Log in
← Back to the A2Z sheet

Step 19 Strings (Advanced Algo) — Advanced Problems (Less asked)

Hashing In Strings

Theory

String hashing converts any substring into a number (its hash) such that equal strings hash equally, letting you compare substrings in O(1) after O(n) preprocessing instead of O(length) character by character. It is the engine inside Rabin-Karp pattern matching and a fast — if probabilistic — alternative to exact algorithms like KMP and Z-function. This lesson derives the polynomial rolling hash, shows the O(1) substring-hash formula with a worked example, and explains collisions and how double hashing controls them.

The polynomial hash and prefix hashes

Map each character to a small positive integer (a=1, b=2, ..., or use its code). Choose a base B (a random small odd number like 31 or 9113823; commonly 31 for lowercase letters) and a large prime modulus M (like 1,000,000,007). The prefix hash is defined by H[0] = 0 and H[i+1] = (H[i] * B + val(s[i])) mod M. So H[i] is the hash of the first i characters, interpreted as digits in base B.

Because the string is being read as a base-B number, appending a character is one multiply-add — and, crucially, a prefix can be 'subtracted' to isolate any substring, as the next section shows. Precompute powers B^0 .. B^n mod M once alongside H.

MOD = 1_000_000_007 BASE = 31 def build_hash(s): n = len(s) H = [0] * (n + 1) P = [1] * (n + 1) for i, ch in enumerate(s): v = ord(ch) - ord('a') + 1 # 1..26, never 0 H[i + 1] = (H[i] * BASE + v) % MOD P[i + 1] = (P[i] * BASE) % MOD return H, P def substring_hash(H, P, l, r): # hash of s[l:r] in O(1) return (H[r] - H[l] * P[r - l]) % MOD

Why the substring formula works — worked example

H[r] contains the whole prefix as a base-B number; the part before l sits in the high positions, multiplied by B^(r-l). Subtracting H[l] * B^(r-l) removes exactly that leading part, leaving the value of s[l:r] as if it started at position 0. Take s = 'abcd' with B = 10 and no modulus for readability (values a=1..d=4): H = [0, 1, 12, 123, 1234]. Hash of 'bc' (l=1, r=3): H[3] - H[1] * 10^2 = 123 - 100 = 23 — and indeed 'bc' read directly is 2*10 + 3 = 23. In code, always take % MOD after subtraction and add MOD if negative (Python's % already returns non-negative for positive modulus).

With this, comparing two substrings for equality, finding the longest repeated substring (binary search length + hash set), or checking palindromes (compare forward and reverse-string hashes) all become O(1)-per-comparison tasks.

Collisions and double hashing

Different strings can share a hash — a collision — either by bad luck or because a problem setter engineered test data against a known base/modulus pair (hash flooding). A single 1e9+7 modulus makes accidental collisions unlikely (roughly one in a billion per comparison), but adversarial cases exist, so the standard defences are: (1) double hashing — compute two hashes with different mod primes (1e9+7 and 1e9+9) or different bases and compare pairs, squaring the safety; (2) use a random base chosen at runtime; (3) in Python, skip the modulus and let arbitrary-precision integers hold the full base-B value, reducing collisions to zero for practical string lengths (at some speed cost) — effectively a 2^64 natural-overflow hash is another common choice in C++ (unsigned long long overflow) with a random odd base.

Character values must start at 1, not 0: with a=0, the strings 'a' and 'aa' would both hash to 0, and leading 'a's would be invisible to the hash.

Rabin-Karp: the headline application

To find a pattern P (length m) in a text T (length n): hash P once, then compare it against the hash of every length-m window of T using the O(1) substring formula. On a hash match, verify character by character (or trust double hashing). Expected total time is O(n + m) — versus O(n*m) naive scanning — because almost every window is rejected by its hash in O(1).

Know the neighbourhood: KMP and Z-function solve the same matching problem exactly in O(n + m) with no collision risk, which is why they have their own lessons in this module. Hashing wins when you need arbitrary substring equality, not just pattern search — repeated substrings, palindrome checks, longest common substring of two strings — where prefix-function methods do not directly apply.

Common mistakes

(1) Using character value 0 for 'a', making leading characters invisible. (2) Forgetting to precompute powers up to n, or indexing P with the wrong length (r - l, not r - l + 1 in this half-open convention) — pick one interval convention and test it on a 1-character substring. (3) Negative intermediate results in languages whose % can return negatives; add MOD before the final %. (4) Trusting a single fixed base/modulus in judged problems known for anti-hash tests — randomise the base or double-hash. (5) Overflow in fixed-width languages when multiplying two mod-sized numbers: use 64-bit intermediates (1e9 * 1e9 fits in 64 bits, not 32).

Key points

  • Prefix polynomial hash: H[i+1] = (H[i]*B + val) mod M turns any substring into a base-B number.
  • Substring hash in O(1): H[r] - H[l] * B^(r-l) mod M — precompute powers once.
  • Character values start at 1; a 0 value makes leading characters disappear from the hash.
  • Collisions are the price: control them with double hashing, a random base, or 64-bit natural overflow.
  • Rabin-Karp uses window hashes for O(n + m) expected matching; hashing also serves substring equality, repeats and palindromes where KMP/Z do not apply.

Suggested questions

Rabin Karp Algorithm ↗ The headline application — slide a window, compare hashes, verify matches.
Z function ↗ The exact, collision-free counterpart for prefix matching — compare the two approaches.
KMP Algorithm or LPS array ↗ Exact pattern matching via the prefix function; no probability involved.
Longest happy prefix ↗ Solvable in O(n) with prefix hashes: compare prefix and suffix hashes for each length.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.