Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Strings & Tries/String Matching (KMP / Z / Rabin-Karp)

Learn the pattern · ~15 min

String Matching (KMP / Z / Rabin-Karp)

also called prefix function, failure function, Z-function, Rabin-Karp

Precompute, for every prefix of the pattern, its longest border (a prefix that is also a suffix). On a mismatch, fall back to that border instead of moving back in the text, so the text is read once.

Signalsfind pattern in textlongest prefix that is also a suffix (border)periodicity / repeated pattern
Cheat sheet and practice

Reach for it when you read

  • +Find where a word occurs in a text (first, last or every occurrence), and n · m comparisons is too slow.
  • +"The longest prefix that is also a suffix", a happy prefix, a border, or the period of a string.
  • +Is the string one block repeated? How short can a repeating unit be?
  • +Make a palindrome by adding letters in front: glue s + '#' + reverse(s) and read the last lps value.
  • +Count strings that avoid a pattern: j (letters matched so far) becomes a DP state.

Not this one when

  • ×Many different patterns, or the longest substring that appears twice: rolling hash (or a suffix structure).
  • ×Two strings with the same letters in any order (anagrams): a frequency count or sliding window, not matching.
  • ×Letters may be skipped (a subsequence, not a substring): two pointers or LCS-style DP.

Learn String Matching (KMP / Z / Rabin-Karp)

First, what are a prefix, a suffix and a border?

Take the word abab. Its prefixes are the pieces that start at the front: a, ab, aba. Its suffixes are the pieces that end at the back: b, ab, bab. (We leave out the whole word itself.)

A piece in both lists is called a border. The longest border of abab is ab, length 2. abc has no border at all.

KMP (Knuth, Morris and Pratt) finds a pattern inside a text and never steps back in the text. First it studies the pattern and writes down, for every prefix, the length of its longest border. That list of numbers is the lps array ("longest prefix that is also a suffix").

How do we build lps?

lps[i] is the length of the longest border of p[0..i]. Let's build it for p = abacabab. We keep one number, len: the border we have so far, which ends at the previous letter. The rule:

Compare the new letter with p[len]. If they are equal, the border grows by one. If not, fall back to the border of that border, len = lps[len − 1], and compare again. Only when len is 0 and it still fails is the answer 0.

lps[0] is always 0.

i letter compare what happens lps[i]
1 b b with p[0] = a no match and len is 0, so there is no border 0
2 a a with p[0] = a match: the border a is born, len becomes 1 1
3 c c with p[1] = b no match, so fall back: len = lps[0] = 0
3 c c with p[0] = a no match again and len is 0: no border 0
4 a a with p[0] = a match, len becomes 1 1
5 b b with p[1] = b match: ab grows, len becomes 2 2
6 a a with p[2] = a match: aba grows, len becomes 3 3
7 b b with p[3] = c no match: abac is not a border. Fall back: len = lps[2] = 1
7 b b with p[1] = b match: the shorter border a grows into ab, len becomes 2 2

So lps = [0, 0, 1, 0, 1, 2, 3, 2]. Notice row 7: aba couldn't grow, so we tried the border of aba, which is a, and that one could.

The code for it

C++
vector<int> buildLps(const string& p) {
    int m = p.size();
    vector<int> lps(m, 0);
    for (int i = 1, len = 0; i < m; ) {
        if (p[i] == p[len]) lps[i++] = ++len;     // the border grows by one
        else if (len > 0) len = lps[len - 1];   // try the next shorter border; i stays
        else lps[i++] = 0;                      // no border at all
    }
    return lps;
}

You don't need to memorise this. It's the table above: "match, grow", "fall back to a shorter border", "nothing left, write 0".

Why fall back to lps[len − 1] and not straight to 0? Because the next border to try is the longest border of the border we just lost. Reset to 0 at i = 7 and we'd compare b with p[0] = a, fail, and write lps[7] = 0. Wrong: ab is a border, so the true value is 2.

Fine, but how does this help us?

Here's the classic problem: find the pattern in a text. Return the first index where p = abacabab starts inside t = abacabacabab, or −1.

By hand, try each start and compare letter by letter:

start how far it gets answer
0 7 letters match, then t[7] = c but p[7] = b no
1 t[1] = b but p[0] = a no
2 t[2] = a matches, then t[3] = c but p[1] = b no
3 t[3] = c but p[0] = a no
4 all 8 letters match yes

The pattern starts at index 4.

The brute force

Every start, compared until a mismatch:

C++
int bruteFind(const string& t, const string& p) {
    int n = t.size(), m = p.size();
    for (int s = 0; s + m <= n; s++) {
        int k = 0;
        while (k < m && t[s + k] == p[k]) k++;
        if (k == m) return s;
    }
    return -1;
}

It's correct, but take a text of n = 10⁶ letters aaa…a (String Matching's limit) and a pattern of m = 5 × 10⁵ letters aa…ab. Every start matches all but the last letter: (n − m + 1) · m ≈ 2.5 × 10¹¹ comparisons, about a minute. Time limit exceeded.

The one thought that fixes it

Stop at start 0, text index 7. We have matched abacaba, the pattern's first 7 letters, and then the text says c where the pattern wants b.

The brute force moves to start 1 and re-reads the text. But we already know those letters: they are the pattern's own first 7, abacaba. So "where can the next match start?" depends only on the pattern.

  • A new start inside these 7 letters only works if the piece from there to the end of abacaba is also its start. That's a border.
  • The longest border of abacaba is aba, length lps[6] = 3. That means the smallest safe slide is 7 − 3 = 4 places: start 4.
  • Any smaller slide would need a longer border, and there isn't one. So no match is skipped.

So keep the 3 matched letters aba, set j = 3, and compare the same text letter c with p[3] = c. It matches, and we never moved back in the text: the same fall-back as in the lps table.

The code for the problem

i walks the text, j counts how many pattern letters are matched right now.

C++
int find(const string& t, const string& p) {
    vector<int> lps = buildLps(p);
    for (int i = 0, j = 0; i < (int)t.size(); i++) {
        while (j > 0 && t[i] != p[j]) j = lps[j - 1];   // keep the border, i stays
        if (t[i] == p[j]) j++;
        if (j == (int)p.size()) return i - j + 1;       // matched all m letters
    }
    return -1;
}

Dry run

Same text and pattern. Watch j.

i t[i] fall-back what happens j after
0–6 a b a c a b a none each letter matches the next pattern letter 1 → 7
7 c j = lps[6] = 3 c ≠ p[7] = b, keep aba; now c = p[3] 4
8–10 a b a none match p[4], p[5], p[6] 5 → 7
11 b none matches p[7]: j = 8 = m 8

j reaches 8 at i = 11, so the match starts at 11 − 8 + 1 = 4, the same answer as the brute force.

Why it's O(n + m)

Count what happens to j. It goes up at most once per text letter, so at most n times. Every fall-back lowers it, and it never goes below 0, so there are at most n fall-backs. The search is O(n), and building lps is O(m) by the same argument with len. Total O(n + m) time, O(m) space for the table.

From O(n · m) down to O(n + m), by never re-reading text we already matched.

Every occurrence? Don't stop at the first

When j reaches m, record the start and fall back as if the next letter had failed, so overlapping matches are found too:

C++
if (j == (int)p.size()) { out.push_back(i - j + 1); j = lps[j - 1]; }

For aba in abababa that gives [0, 2, 4]: the matches overlap, and the fall-back to lps[2] = 1 keeps the shared a.

Longest prefix that is also a suffix? Read the last value

That's the longest border of the whole string, lps[n − 1]: 2 for abacabab, the piece ab. That's all Longest Happy Prefix asks.

Is the string one block repeated?

Let L = lps[n − 1]. If L > 0 and n % (n − L) == 0, the string is its first n − L letters repeated. abcabcabc has L = 6, and 9 % 3 = 0: it's abc three times. abacabab has L = 2, and 8 % 6 ≠ 0: no.

Remember this

  • lps[i] = the longest border of p[0..i]. Build it before you touch the text.
  • On a mismatch, j = lps[j − 1] and i stays. Resetting j to 0 misses matches; moving i back makes it O(n · m) again.
  • while for the fall-back, not if: one fall-back may not be enough.
  • Whenever a problem asks "where does this word occur" or "the longest prefix that is also a suffix", it's an lps question.

Practise it on Find the Index of the First Occurrence in a String, then String Matching (every occurrence), Longest Happy Prefix, Repeated Substring Pattern and Shortest Palindrome (lps of s + '#' + reverse(s)).

Watch it work, line by line

Find the Index of the First Occurrence in a String ↗, text = "ababcabcabababd", pattern = "ababd" → 10. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Am I searching for one fixed pattern in a text, or asking about a string's prefixes that are also suffixes (borders, periods, repeats)?

Reach for it when

  • +find pattern in text
  • +longest prefix that is also a suffix (border)
  • +periodicity / repeated pattern
  • +shortest palindrome by adding a prefix
  • +n + m up to 1e6

It fails when

  • ×Many patterns at onceuse Aho-Corasick
  • ×Substring order or LCP queriesuse Suffix array
  • ×Palindromic substringsuse Manacher

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1What does lps[i] mean?Reveal

    The length of the longest proper prefix of p[0..i] that is also a suffix of it.

  • 2On a mismatch with j > 0, what changes and what doesn't?Reveal

    j = lps[j − 1]. The text index i stays where it is, and the same letter is tried again.

  • 3Why is KMP O(n + m) despite the inner while?Reveal

    j goes up by at most 1 per text letter, and each fall-back lowers it. It can't fall more often than it rose.

Practice ladder

every problem →
  1. 1Find the Index of the First Occurrence in a Stringthe hookEasy
  2. 2String Matchingevery occurrenceMedium
  3. 3Repeated Substring Patternread the last lps valueEasy
  4. 4Longest Happy Prefixread the last lps valueHard
  5. 5Finding PeriodsperiodsMedium
  6. 6Shortest Palindromeglue two stringsHard
  7. 7Required Substringthe pattern as a state machineHard
  8. 8Repeated DNA Sequencesrolling hashMedium
  9. 9Longest Duplicate Substringhash plus binary searchHard

Finished String Matching (KMP / Z / Rabin-Karp)? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to String Matching (KMP / Z / Rabin-Karp)

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial