1. Prefix hash
Each prefix hash extends the previous one by one character.
prefix[i + 1] = (prefix[i] * base + s.charCodeAt(i)) % modTyporithm · hard
Step 1 of 8 · intro card
String Algorithms
Precompute prefix hashes and base powers so any substring's hash is one O(1) formula.
A polynomial hash treats a string as a number in a chosen base, modulo a large prime.
Storing prefix hashes lets any substring hash be derived by subtracting an aligned prefix.
After an O(n) build, every substring comparison becomes an O(1) hash lookup.
Prefix hashes build in O(n).
Align with precomputed powers.
Substring hash is O(1).
function buildHashes(s) {
const n = s.length;
const base = 131;
const mod = 1000000007;
const prefix = new Array(n + 1).fill(0);
const power = new Array(n + 1).fill(1);
for (let i = 0; i < n; i += 1) {
prefix[i + 1] = (prefix[i] * base + s.charCodeAt(i)) % mod;
power[i + 1] = (power[i] * base) % mod;
}
return function substringHash(left, right) {
const span = right - left + 1;
return ((prefix[right + 1] - prefix[left] * power[span]) % mod + mod) % mod;
};
}Connect each part of the code to the concept before you type.
Each prefix hash extends the previous one by one character.
prefix[i + 1] = (prefix[i] * base + s.charCodeAt(i)) % modPrecompute base^k to align prefix hashes during subtraction.
power[i + 1] = (power[i] * base) % modCombine two prefix hashes to get any substring's hash in O(1).
return ((prefix[right + 1] - prefix[left] * power[span]) % mod + mod) % modRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputString apply · base 131 · modulus 1000000007
The prefix hash table above and powers buffer below each hold n + 1 entries. The input array is not counted as extra space.
↗ The 1-cell working table above is itself auxiliary memory. Input values are shown separately.
Powers1 entries
Input · not auxiliary memory
Characters5 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state