Skip to content
We areTOP 1%
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;
}

Problems

String Algorithms (KMP, Z, Hashing) questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Longest Happy PrefixLeetCodeHard Solve Longest Happy Prefix on LeetCode (opens in a new tab)
2PasswordCodeforcesMedium 1700Solve Password on Codeforces (opens in a new tab)
3Shortest PalindromeLeetCodeHard Solve Shortest Palindrome on LeetCode (opens in a new tab)
4Prefix-Suffix Palindrome (Hard version)CodeforcesHard 1800Solve Prefix-Suffix Palindrome (Hard version) on Codeforces (opens in a new tab)
5Sum of Scores of Built StringsLeetCodeHard Solve Sum of Scores of Built Strings on LeetCode (opens in a new tab)
6Tavas and MalekasCodeforcesHard 1900Solve Tavas and Malekas on Codeforces (opens in a new tab)
7Longest Duplicate SubstringLeetCodeHard Solve Longest Duplicate Substring on LeetCode (opens in a new tab)
8Prefixes and SuffixesCodeforcesHard 2000Solve Prefixes and Suffixes on Codeforces (opens in a new tab)
9Watto and MechanismCodeforcesHard 2000Solve Watto and Mechanism on Codeforces (opens in a new tab)
10Palindrome DegreeCodeforcesHard 2200Solve Palindrome Degree on Codeforces (opens in a new tab)
11Anthem of BerlandCodeforcesHard 2300Solve Anthem of Berland on Codeforces (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account