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, textpatterntextpattern
Example 1
Output: [0, 9, 12]
Example 2
Output: [0, 3]
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 textpattern
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.
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
So lps[i]
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| pattern[i] | A | B | A | B | C | A | B | A | B |
| lps[i] | 0 | 0 | 1 | 2 | 0 | 1 | 2 | 3 | 4 |
For example, lps[3]lps[8]
Building the lps table
How do we fill the table without checking every piece of every beginning? Move ilenipattern[i]pattern[len]
- If they are equal, the border grows by one:
becomeslps[i] .len + 1 - If not, and
is above 0, try the next shorter border,len , and compare again.len = lps[len - 1] - If not, and
is 0, no border ends here:len is 0.lps[i]
Why is lps[len - 1]lenpattern[2]lenlps[1]pattern[0]lps[4]
Searching with the table
How does the search use the table? It keeps jitext[i]pattern[j]jjlps[j - 1]j
When jii - m + 1jlps[m - 1]j
Java Solution
The two methods work in these steps:
- First,
creates the arraybuildLps(pattern) , one entry per pattern character, and the border lengthlps , starting at 0.len - A
loop moveswhile from 1 to the end of the pattern. Each pass grows the border, falls back withi without movinglen = lps[len - 1] , or writes 0 and moves on.i - Then
creates the listsearch(text, pattern) , buildsresult , and sets the match countlps to 0.j - A
loop movesfor over the text once. Inside it, ai loop setswhile for as long asj = lps[j - 1] is above 0 and the text character differs fromj .pattern.charAt(j) - If the text character now equals
,pattern.charAt(j) goes up by one.j - When
equals the pattern's length, addj toi - j + 1 and setresult . After the loop, returnj = lps[j - 1] .result
The main
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:
[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]
Look at [0, 1, 2]j = lps[j - 1]j = 0[0, 2][0, 9]
The line [3]j
Complexity
The work is building the table once, plus one pass over the text.
- Time: O(n + m).
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.j takes O(m) by the same count onbuildLps .len - Space: O(m) for the
array, onelps per pattern character, besides the list of positions returned.int
The