KMP String Matching

Find every place a pattern occurs in a text, reading the text from left to right without ever going back.

Given two strings, text and pattern, return every position in text where a copy of pattern starts, from left to right. Positions count from 0, and two copies may overlap. Solve it with the Knuth-Morris-Pratt (KMP) algorithm, which goes through the text once and never steps back.

Example 1
Input: text = "AABAACAADAABAABA", pattern = "AABA"
Output: [0, 9, 12]
Example 2
Input: text = "abcabc", pattern = "abc"
Output: [0, 3]
Solution

The Idea

When you press Ctrl+F in a browser and type a word, the browser finds every place that word appears on the page. This problem is the same search: the page is text and the word is pattern.

The plainest way is to line the pattern up under each position of the text and compare character by character. In Example 1, "AABA" under position 0 agrees in all four characters, so 0 is a match. Under position 1, the first A agrees, but the text has B where the pattern has its second A, so that try fails. The search goes on like this up to position 12, the last place where four characters still fit.

Now look at what happens right after the match at 9. The plain search moves on to position 10 and compares text positions 10, 11 and 12 again, though it read them a moment ago. Does it have to? Those characters are already known: they are the pattern's own characters, because the pattern has just matched there.

Look at the picture below. The row labelled match at 9 shows "AABA" under text positions 9 to 12. Its last A, at position 12, is also the first character of the pattern.

The text AABAACAADAABAABA with the pattern AABA matched at 9. The last A of that match is the first A of the pattern, so the next try starts at 12 with one character already matched. Starts 10 and 11 are skipped.

So the row labelled next try at 12 can begin with that A already matched, and carry on comparing at text position 13. The row labelled skipped starts holds 10 and 11, and neither can start a copy. A copy at 10 would need "AAB" at positions 10 to 12, but the text there reads "ABA". A copy at 11 would need "AA" at positions 11 and 12, but the text reads "BA".

Every one of those checks compared the pattern with a piece of itself, never with the unknown rest of the text. So the place to try next depends only on the pattern and on how many of its characters have matched. That can be worked out once, before the search begins, and then the search walks through the text from left to right without going back.

Solution Approach

Turning that idea into code means first seeing why the plain search is slow, then settling three things: what to remember about the pattern, how to work it out, and how the search uses it, overlapping copies included.

The plain search and its cost

How slow is the plain search? Call the length of the text n and the length of the pattern m. There are n - m + 1 starting positions, and each one can take up to m comparisons, so the work grows like n × m.

That worst case is easy to reach. Take a text of one million a's and a pattern of 999 a's followed by one b. Every start agrees for 999 characters and only then fails on the b, about a billion comparisons in total.

What to remember about the pattern

What exactly does the search need to know about the pattern? Suppose its first k characters have matched. The next try can only work where the start of the pattern lines up with the end of those k characters. So we need a piece that is both a beginning and an ending of the first k characters, and shorter than all k.

Such a piece is called a border. "AABA" has the border "A", which is how the picture jumped from 9 to 12. "ABAB" has the border "AB". The search always takes the longest border, because that is the smallest move, so no possible copy gets jumped over.

The search needs the length of the longest border for every beginning of the pattern, and these lengths go into an array usually called lps. The name stands for "longest proper prefix that is also a suffix". A prefix is a beginning of the string, a suffix is an ending, and proper means shorter than the whole string.

So lps[i] is the length of the longest border of the pattern's characters 0 to i. For "ABABCABAB" it looks like this:

i012345678
pattern[i]ABABCABAB
lps[i]001201234

For example, lps[3] is 2 because "ABAB" starts and ends with "AB". lps[8] is 4 because the whole pattern starts and ends with "ABAB". At position 4, the C, nothing that begins with A can end there, so the value is 0.

Building the lps table

How do we fill the table without checking every piece of every beginning? Move i along the pattern from position 1, and keep len, the length of the longest border of the characters before i. Then compare pattern[i] with pattern[len], the character just after that border:

  • If they are equal, the border grows by one: lps[i] becomes len + 1.
  • If not, and len is above 0, try the next shorter border, len = lps[len - 1], and compare again.
  • If not, and len is 0, no border ends here: lps[i] is 0.

Why is lps[len - 1] the next border to try? The current border appears at both the start and the end, so a border of that border also sits at both ends. In "ABABCABAB", at the C, len is 2. C differs from pattern[2], an A, so len drops to lps[1], which is 0. C also differs from pattern[0], so lps[4] is 0.

Searching with the table

How does the search use the table? It keeps j, the number of pattern characters matched so far, while i moves along the text. If text[i] equals pattern[j], j grows by one. If not, j drops to lps[j - 1] and the same text character is compared again, until it matches or j is 0.

When j reaches m, a copy ends at i, so it starts at i - m + 1. To find a copy that overlaps this one, j drops to lps[m - 1] rather than 0. In Example 1 that sets j to 1 after the match at 9, which is the row labelled next try at 12 in the picture.

Java Solution

The two methods work in these steps:

  1. First, buildLps(pattern) creates the array lps, one entry per pattern character, and the border length len, starting at 0.
  2. A while loop moves i from 1 to the end of the pattern. Each pass grows the border, falls back with len = lps[len - 1] without moving i, or writes 0 and moves on.
  3. Then search(text, pattern) creates the list result, builds lps, and sets the match count j to 0.
  4. A for loop moves i over the text once. Inside it, a while loop sets j = lps[j - 1] for as long as j is above 0 and the text character differs from pattern.charAt(j).
  5. If the text character now equals pattern.charAt(j), j goes up by one.
  6. When j equals the pattern's length, add i - j + 1 to result and set j = lps[j - 1]. After the loop, return result.

The main method prints the tables for "AABA" and "ABABCABAB", runs both examples, then searches for a pattern that overlaps itself, one that fails on its last character, one longer than the text, and one that never occurs.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class KMPStringMatching {

    // lps[i]: length of the longest border of pattern[0..i]
    public static int[] buildLps(String pattern) {
        int[] lps = new int[pattern.length()];
        int len = 0;                          // length of the current border
        int i = 1;
        while (i < pattern.length()) {
            if (pattern.charAt(i) == pattern.charAt(len)) {
                lps[i++] = ++len;             // the border grows by one
            } else if (len > 0) {
                len = lps[len - 1];           // try the next shorter border
            } else {
                lps[i++] = 0;                 // no border ends here
            }
        }
        return lps;
    }

    public static List<Integer> search(String text, String pattern) {
        List<Integer> result = new ArrayList<>();
        int[] lps = buildLps(pattern);
        int j = 0;                            // pattern characters matched so far
        for (int i = 0; i < text.length(); i++) {
            while (j > 0 && text.charAt(i) != pattern.charAt(j)) {
                j = lps[j - 1];               // fall back without moving i
            }
            if (text.charAt(i) == pattern.charAt(j)) {
                j++;
            }
            if (j == pattern.length()) {
                result.add(i - j + 1);        // the match started j - 1 places back
                j = lps[j - 1];               // keep the overlap for the next match
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(buildLps("AABA")));
        System.out.println(Arrays.toString(buildLps("ABABCABAB")));
        System.out.println(search("AABAACAADAABAABA", "AABA"));
        System.out.println(search("abcabc", "abc"));
        System.out.println(search("aaaa", "aa"));
        System.out.println(search("abcabd", "abd"));
        System.out.println(search("abc", "abcd"));
        System.out.println(search("hello", "xyz"));
    }
}

Running it prints:

Output
[0, 1, 0, 1]
[0, 0, 1, 2, 0, 1, 2, 3, 4]
[0, 9, 12]
[0, 3]
[0, 1, 2]
[3]
[]
[]

The table for "AABA" is [0, 1, 0, 1], and its last 1 is the border "A" from the picture. The next line matches the table for "ABABCABAB" in Solution Approach, ending in the 4 of the border "ABAB".

Look at [0, 1, 2]: "aa" sits in "aaaa" three times, each copy sharing an a with the next. That is what j = lps[j - 1] after a match buys. A version that sets j = 0 there instead prints [0, 2] for this input and [0, 9] for Example 1, losing every overlapping copy.

The line [3] comes from "abd" in "abcabd". The first try matches "ab", then finds c where d should be; "ab" has no border, so j drops to 0 and the copy at 3 is found later. The two empty lists come from "abcd", longer than its text, and "xyz", which never appears in "hello".

Complexity

The work is building the table once, plus one pass over the text.

  • Time: O(n + m). j rises by at most one for each of the n text characters, and every fall-back lowers it, so the fall-backs add up to at most n. buildLps takes O(m) by the same count on len.
  • Space: O(m) for the lps array, one int per pattern character, besides the list of positions returned.

The Z-function solves the same search in the same time, with a different table.