DSA · Competitive Programmer · Pattern 7 of 9
String Algorithms (KMP, Z, Hashing)
11 problems.
Your progress0%
- 1st Visit
- 0/11
- 2nd Visit
- 0/11
- Revise
- 0/11
About this pattern
Linear-time string matching avoids the O(nm) cost of comparing a pattern at every position. The prefix function from KMP gives, for each prefix, the length of its longest proper border, a prefix that is also a suffix; running it on pattern + '#' + text finds every occurrence. The Z-function gives, for each position, the length of the longest substring starting there that matches a prefix of the string. Polynomial hashing compares any two substrings in O(1) after O(n) preprocessing, at the cost of a small collision risk. Signals: repeated prefix and suffix structure, palindromic prefixes, overlaps between consecutive strings, or substring comparisons inside a binary search.
vector<int> prefixFunction(const string& s) {
vector<int> pi(s.size(), 0);
for (int i = 1; i < (int)s.size(); i++) {
int k = pi[i - 1];
while (k > 0 && s[i] != s[k]) k = pi[k - 1];
pi[i] = k + (s[i] == s[k]);
}
return pi;
}
vector<int> zFunction(const string& s) {
vector<int> z(s.size(), 0);
for (int i = 1, l = 0, r = 0, n = s.size(); i < n; i++) {
if (i < r) z[i] = min(r - i, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;
if (i + z[i] > r) { l = i; r = i + z[i]; }
}
return z;
}