Lesson 41 · Core algorithms

String Hashing

Treat a string as a number in base B modulo a prime. With prefix hashes and powers stored once, any substring's hash costs O(1), and equal hashes mean almost certainly equal strings.

String Hashing concept diagramA visual explanation of the layout and operations shown in this lesson.a prefix table answers any substring hash in constant timeabcabH0H1H2H3H4H5substring [2,4)hash = H4 − H2 × base²equal hashes still need one direct comparison — collisions are possible
1

What String Hashing Does

String hashing maps a string to a single number, its hash, so that two strings can be compared by comparing two numbers. Comparing letters costs O(length); comparing hashes costs O(1).

The trick that makes it useful is not hashing one string but hashing every substring of a string quickly. After one O(n) pass, the hash of any substring can be read off in constant time. That turns many string problems from O(n²) or worse into O(n) or O(n log n).

The price is a small chance of error. Two different strings can share a hash, so an equal hash says "almost certainly equal", never "certainly".

  • Equal strings always get equal hashes
  • Unequal hashes always mean unequal strings
  • Equal hashes mean equal strings with high probability
2

The Polynomial Hash

The standard choice is a polynomial hash. Give each character a value, pick a base B and a prime modulus M, and read the string as a number in base B: hash(s) = s₀·Bⁿ⁻¹ + s₁·Bⁿ⁻² + … + sₙ₋₁ (mod M). The position of each letter changes its weight, so "ab" and "ba" get different hashes.

Character values must start at 1, not 0. If a were 0, then "a", "aa" and "aaa" would all hash to 0. With lowercase letters only, a = 1 … z = 26 and B = 31 is the usual pick; with mixed case, B = 53. Any base larger than the alphabet works.

M is a large prime such as 1,000,000,007 or 1,000,000,009. Both values stay below 2³⁰, so the product of two of them fits in a signed 64-bit integer before taking the remainder.

  • Base above the alphabet size: 31 for lowercase, 53 for mixed case
  • Prime modulus near 10⁹, so products fit in 64 bits
  • Character values from 1, never 0
3

Prefix Hashes: Any Substring Hash in O(1)

  1. Map each character to a value from 1 up
  2. Build H[0..n] and P[0..n] in one pass
  3. For [l, r), compute H[r] − H[l]·P[r − l]
  4. Add M, then take the remainder, so the result is never negative
  5. Compare hashes only between substrings of the same length

Store H[k], the prefix hash of the first k characters, with H[0] = 0 and H[k+1] = H[k]·B + s[k]. Store the powers P[k] = Bᵏ alongside it. Both tables take one pass.

For the half-open range [l, r), H[r] contains H[l] shifted up r − l places, followed by exactly the characters of the substring. Shift H[l] by the same amount and subtract: hash(l, r) = H[r] − H[l]·P[r − l] (mod M). That is the substring hash in two lookups and one multiply.

On "banana" with a = 1 and B = 31: H = 0, 2, 63, 1967, 60978, 1890332, 58600293. "ana" at [1, 4) is 60978 − 2·29791 = 1396, and "ana" at [3, 6) is 58600293 − 1967·29791 = 1396 as well. "nan" at [2, 5) is 13499, so it differs from both.

  • Preprocessing O(n) time and memory
  • Each substring hash O(1)
  • The power is the substring length, r − l
Key reference

Terms, operations, and practical uses

Building the hash

  • Base BThe multiplier for each position. Larger than the number of distinct characters; 31 for lowercase letters.
  • Modulus MA large prime that keeps values bounded, usually 1,000,000,007 or 1,000,000,009.
  • Character valueThe number for each character, starting at 1 so no character can vanish from the sum.

Substring queries

  • Prefix hash H[k]Hash of the first k characters. H[0] = 0 and H[k+1] = H[k]·B + s[k] mod M.
  • Power table P[k]Bᵏ mod M, stored so the shift for any length is one lookup.
  • Substring hashFor [l, r): (H[r] − H[l]·P[r − l]) mod M, made non-negative by adding M.

Collisions

  • CollisionTwo different strings with the same hash, like "Aa" and "BB" under Java's hashCode.
  • Birthday boundWith n hashes, about n²/(2M) colliding pairs are expected, so trouble starts near √M hashes.
  • Double hashingTwo independent moduli used together; the pair collides only if both parts do.
Implementation

Code in Python, C++ and Java

B, M = 31, 1_000_000_007


def prefix_hashes(s):
    h, p = [0], [1]
    for ch in s:
        h.append((h[-1] * B + ord(ch) - ord("a") + 1) % M)
        p.append(p[-1] * B % M)
    return h, p


def sub_hash(h, p, l, r):
    return (h[r] - h[l] * p[r - l]) % M


s = "banana"
h, p = prefix_hashes(s)
print("ana at 1:", sub_hash(h, p, 1, 4))
print("ana at 3:", sub_hash(h, p, 3, 6))
print("ban vs nan:", sub_hash(h, p, 0, 3), sub_hash(h, p, 2, 5))

seen = set()
for i in range(len(s) - 2):
    x = sub_hash(h, p, i, i + 3)
    if x in seen:
        print("Repeated length-3 substring:", s[i:i + 3])
        break
    seen.add(x)
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;

const long long B = 31, M = 1000000007;
vector<long long> h, p;

void prefixHashes(const string& s) {
    h.assign(s.size() + 1, 0);
    p.assign(s.size() + 1, 1);
    for (size_t i = 0; i < s.size(); i++) {
        h[i + 1] = (h[i] * B + (s[i] - 'a' + 1)) % M;
        p[i + 1] = p[i] * B % M;
    }
}

long long subHash(int l, int r) {
    return ((h[r] - h[l] * p[r - l]) % M + M) % M;
}

int main() {
    string s = "banana";
    prefixHashes(s);
    cout << "ana at 1: " << subHash(1, 4) << "\n";
    cout << "ana at 3: " << subHash(3, 6) << "\n";
    cout << "ban vs nan: " << subHash(0, 3) << " " << subHash(2, 5) << "\n";

    unordered_set<long long> seen;
    for (int i = 0; i + 3 <= (int)s.size(); i++) {
        long long x = subHash(i, i + 3);
        if (seen.count(x)) {
            cout << "Repeated length-3 substring: " << s.substr(i, 3) << "\n";
            break;
        }
        seen.insert(x);
    }
}
import java.util.HashSet;
import java.util.Set;

public class Main {
    static final long B = 31, M = 1_000_000_007L;
    static long[] h, p;

    static void prefixHashes(String s) {
        h = new long[s.length() + 1];
        p = new long[s.length() + 1];
        p[0] = 1;
        for (int i = 0; i < s.length(); i++) {
            h[i + 1] = (h[i] * B + (s.charAt(i) - 'a' + 1)) % M;
            p[i + 1] = p[i] * B % M;
        }
    }

    static long subHash(int l, int r) {
        return ((h[r] - h[l] * p[r - l]) % M + M) % M;
    }

    public static void main(String[] args) {
        String s = "banana";
        prefixHashes(s);
        System.out.println("ana at 1: " + subHash(1, 4));
        System.out.println("ana at 3: " + subHash(3, 6));
        System.out.println("ban vs nan: " + subHash(0, 3) + " " + subHash(2, 5));

        Set<Long> seen = new HashSet<>();
        for (int i = 0; i + 3 <= s.length(); i++) {
            long x = subHash(i, i + 3);
            if (!seen.add(x)) {
                System.out.println("Repeated length-3 substring: " + s.substring(i, i + 3));
                break;
            }
        }
    }
}
Watch it run

Step through it

Running on "banana", a=1 ... z=26, base 31, modulus 1,000,000,007

banana with a = 1 ... z = 260b= 21a= 12n= 143a= 14n= 145a= 1kprefixH[k]0(empty)0base B = 31, modulus M = 1,000,000,007H[0] = 0: the empty prefix has hash 0
Step 1

Letters become numbers

Map a to 1, b to 2 and so on up to z = 26, so "banana" becomes 2, 1, 14, 1, 14, 1. No letter maps to 0: if a were 0, then "a", "aa" and "aaa" would all hash to 0. The base is 31, a prime just above the alphabet size, and every sum is taken modulo 1,000,000,007.

Output
1 / 12
4

Collisions and the Birthday Bound

A collision is two different strings with the same hash. They cannot be avoided: there are endlessly many strings and only M hash values. Java's String.hashCode uses this polynomial with B = 31 and no prime modulus, and "Aa" and "BB" both hash to 2112.

For two fixed strings and a random base, the chance of a collision with modulus M is about 1/M, roughly one in a billion. The danger is comparing many hashes at once. With 100,000 substrings in a set there are about 5 billion pairs, so about 5 collisions are expected. This is the birthday paradox: collisions appear after about √M hashes, not M.

The fix is double hashing: compute the hash with two independent moduli and treat the pair as the key. The value space becomes about 10¹⁸, and the expected count for 100,000 substrings falls to about 5 in a billion. Pick the base at random when inputs may be chosen to break you; hashing modulo 2⁶⁴ by plain overflow is known to fail on Thue-Morse strings for any base.

  • One hash, two strings: collision chance about 1/M
  • n hashes compared pairwise: about n²/(2M) collisions
  • Two moduli or a check of the letters when a wrong answer matters
5

Problems String Hashing Solves

Any task that compares many substrings benefits. Hash every substring of a fixed length and put the hashes in a set to find repeats, as in Repeated DNA Sequences. Hash all substrings to count the distinct ones, as in Number of Distinct Substrings.

Binary search on length plus hashing finds the longest common prefix of two suffixes in O(log n), and the longest repeated substring in O(n log n). Hashing a string and its reverse checks whether any substring is a palindrome in O(1). Searching a text for a pattern by hashing each window is the Rabin-Karp algorithm.

Hashing vs an exact method
TaskWith hashingExact alternative
Is s[a..b) equal to s[c..d)?O(1) after O(n)O(length) letter by letter
Find a pattern in a textO(n + m) expectedKMP or Z algorithm, O(n + m)
Longest repeated substringO(n log n), binary searchSuffix array, O(n log n)
Can it be wrong?Yes, rarelyNo
  • Best when one string is asked many substring questions
  • Simpler to write than suffix structures
  • Use an exact method when a single wrong answer is unacceptable
6

Common Mistakes

Most hashing bugs give wrong answers silently, so they are worth knowing in advance.

  • Mapping a character to 0, so strings that differ only in leading copies of it collide
  • Multiplying H[l] by B instead of B to the power r − l
  • Forgetting that C++ and Java keep the sign in %: (x % M + M) % M
  • Multiplying two values near M in 32-bit integers, which overflows
  • Comparing hashes of substrings with different lengths
  • Comparing hashes built with different bases, moduli or character maps
  • Using one modulus for millions of hashes in one set