Arrays & Hashing · Pattern 21 of 26

KMP: string matching in O(n + m)

The prefix function lps[i] is the length of the longest proper prefix of the pattern that is also a suffix ending at i. On a mismatch, jump back to lps instead of restarting, so nothing is compared twice.

3 variations · 3 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Find a pattern in a text in linear time
  • Longest prefix that is also a suffix
  • Repeated or periodic strings

The template

String Matching (KMP)
int strStr(String text, String pat) {
    if (pat.isEmpty()) return 0;
    int[] lps = new int[pat.length()];          // lps[i]: longest prefix = suffix of pat[0..i]
    for (int i = 1, k = 0; i < pat.length(); i++) {
        while (k > 0 && pat.charAt(i) != pat.charAt(k)) k = lps[k - 1];
        if (pat.charAt(i) == pat.charAt(k)) k++;
        lps[i] = k;
    }
    for (int i = 0, k = 0; i < text.length(); i++) {
        while (k > 0 && text.charAt(i) != pat.charAt(k)) k = lps[k - 1];   // fall back, never restart
        if (text.charAt(i) == pat.charAt(k)) k++;
        if (k == pat.length()) return i - k + 1;
    }
    return -1;
}

The variations

  1. 1The prefix function

    lps of the whole string answers "longest prefix that is also a suffix" directly: it is lps[n − 1].

  2. 2Find a pattern in a text

    Run the same fall-back loop over the text. When k reaches the pattern length you found a match ending at i.

  3. 3More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Starting the lps loop at i = 0: lps[0] is always 0 because the prefix must be proper.
  • Falling back with k = lps[k] instead of lps[k - 1].
Next: Math and number theory →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.