The Knuth-Morris-Pratt string searching algorithm searches for occurrences of a "pattern" string within a main string by employing the simple observation that when a mismatch occurs, we have enough knowledge simply by possessing the pattern to determine where the next match could begin, thus bypassing re-examination of previously matched characters.
The algorithm was invented by Knuth and Pratt and independently by J. H. Morris in 1976
The KMP Algorithm
To motivate the technical details, we consider a specific instance. In this article, we will be using zero-based arrays for our strings; thus the 'C' in will be denoted . Let be the start of the currently matched substring within and the position within .
m: 01234567890123456789012 S: ABC ABCDAB ABCDABCDABDE P: ABCDABD i: 0123456
We begin a step by matching each character one after another. Thus in the fourth step, and . But is a space and , so we have a mismatch. Rather than beginning again at , we note that no 'A' occurs between positions 0 and 3 in except at 0; hence, having checked all those characters previously, we know there is no chance of finding the beginning of a match if we check them again. Therefore we move on to the next character, setting and .
m: 01234567890123456789012 S: ABC ABCDAB ABCDABCDABDE P: ABCDABD i: 0123456
We quickly obtain a nearly complete match 'ABCDAB' when, at , we again have a discrepancy. However, just prior to the end of the current partial match, we passed an 'AB' which could be the beginning of a new match, so we must take this into consideration. As we already know that these characters match the two characters prior to the current position, we need not check them again; we simply reset , and continue matching the current character.
m: 01234567890123456789012 S: ABC ABCDAB ABCDABCDABDE P: ABCDABD i: 0123456
This search fails immediately, however, as the pattern still does not contain a space, so as in the first trial, we increment , reset , and begin searching anew.
m: 01234567890123456789012 S: ABC ABCDAB ABCDABCDABDE P: ABCDABD i: 0123456
Once again we immediately hit upon a match 'ABCDAB' but the next character, 'C', does not match the final character 'D' of the pattern. Reasoning as before, we set , to start at the two-character string 'AB' leading up to the current position, set , and continue matching from the current position.
m: 01234567890123456789012 S: ABC ABCDAB ABCDABCDABDE P: ABCDABD i: 0123456
This time we are able to complete the match, and return the position 17 as its origin.
The search algorithm
The above example is completely instructive in this regard. We assume the existence of a "partial match" table, described below, which indicates where we need to look for the start of a new match in the event that the current one ends in a mismatch. For the moment the table, , should be taken as a black box with the property that if we have a match starting at that fails when comparing to , then the next possible match will start at . In particular, is defined and equals . Knowing this, the algorithm is very simple:
- Let ; say has characters, and , characters.
- If , then we exit; there is no match. Otherwise, compare versus . At this point we have already matched previous characters.
- If they are equal, set . If then we have found a full match; terminate the algorithm and return as the start of the match.
- If they are unequal, let be the entry in the "partial match" table described below at position . Set , .
- Return to step 2.
This clearly implements the algorithm performed in the example; at each mismatch, we consult the table for the next known possible beginning of a new match and update our counters accordingly. Thus we need never backtrack; in particular, each character is matched only once (though potentially mismatched many times; an analysis of the efficiency of this algorithm is given below).
The efficiency of the search algorithm
Assuming the prior existence of the table , the search portion of the Knuth-Morris-Pratt algorithm has complexity , where is the length of . We compute this by counting the number of times each step can execute. The crucial stages are the two branches of step 2; the total number of times they execute is the number of times step 2 itself executes. The important fact about the second branch is that the value of is guaranteed to increase by at least 1. Since we set , increases if and only if . By definition, is the length of a proper terminal substring of the characters ; hence is at most . This argument holds when ; when we have , so the inequality again holds. Therefore does indeed increase in the second branch, so this branch is executed at most times, as the algorithm terminates when .
The second branch of step 2 executes once each time a comparison is not a match; the first branch, likewise, executes once for each match. It is clear from the operations performed in the second branch that is nondecreasing with successive iterations of step 2; therefore, since actually increases each time the first branch executes, the index of the character currently under scrutiny increases between successive iterations of the first branch. Hence a character which has once been matched is never subjected to comparison again. It follows that the first branch also executes at most once for each character of , hence no more than times. So step 2 executes at most times. As step 1 executes merely once, and step 3 executes each time step 2 does except when the algorithm exits, the number of steps performed by the algorithm in searching is at most ; hence the search algorithm exits in time.
A code example of the search algorithm
Sample C code for an implementation of this algorithm is given below. In order to satisfy the natural limitations on the bounds of C arrays, in the code is equivalent to above.
int kmp_search(char *P, char *S) { extern int T[]; int m = 0; int i = 0; while (S[m + i] != '\0' && P[i] != '\0') { if (S[m + i] == P[i]) { ++i; } else { m += i - T[i]; i = T[i]; } } return m; }
The "partial match" table
The goal of the table is to allow the algorithm not to check any character of the main string more than once. The key observation about the nature of a linear search that allows this to happen is that in having checked some segment of the main string against an initial segment of the pattern, we know exactly at which places a new potential match which could continue to the current position could begin prior to the current position. In other words, we "pre-search" the pattern itself and compile a list of all possible fallback positions that bypass a maximum of hopeless characters while not sacrificing any potential matches in doing so.
We want to be able to look up, for each pattern position, the length of the longest possible initial match that ends in the current position other than the full match that probably just failed. Hence is exactly the length of the longest possible initial segment of which is also a terminal segment of the substring ending at . We use the convention that the empty string has length 0. Since a mismatch at the very start of the pattern is a special case (there is no possibility of backtracking), we set , as discussed above.
We consider the example of 'ABCDABD' first. We will see that it follows much the same pattern as the main search, and is efficient for similar reasons. We set . Since is at the end of only the complete initial segment, we set as well. To find , we must discover a proper terminal substring of 'AB' which is also an initial substring of the pattern. But the only proper terminal substring of 'AB' is 'B', which is not an initial substring of the pattern, so we set .
Continuing to 'C', we note that there is a shortcut to checking all terminal substrings: let us say that we discovered a terminal substring ending at 'C' with length 2; then its first character is an initial substring of an initial substring of the pattern, hence an initial substring itself...and it ends at 'B', which we already determined cannot occur. Therefore we need not even concern ourselves with substrings having length 2, and as in the previous case the sole one with length 1 fails, so .
Similarly for 'D', giving , so we pass to the subsequent 'A'. The same logic shows that the longest substring we need consider has length 1, and in this case 'A' does work; thus . Considering now the following 'B', we exercise the following logic: if we were to find a subpattern beginning before the previous 'A' yet continuing to the current 'B', then in particular it would itself have a proper initial segment ending at 'A' yet beginning before 'A', which contradicts the fact that we already found that 'A' itself is the earliest occurrence of a proper subpattern ending at it. Therefore we need not look before that 'A' to find a subpattern for 'B'. In fact, checking it, we find that it continues to 'B' and that 'B' is the second entry of the substring of which 'A' is the first. Therefore the entry for 'B' in 'T' is one more than the entry for 'A', namely .
Finally, the pattern does not continue from 'B' to 'D'. Similar reasoning as above shows that if we were to find a subpattern longer than 1 at 'D' then it must comprise a subpattern ending at 'B'; since the current one does not work, this one would have to be shorter. But the current one is an initial segment of the pattern ending at the second position, so this potential new subpattern would be as well, and we already decided there were none of those. Since 'D' itself is not a subpattern, .
Therefore we compile the following table:
-1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
A | B | C | D | A | B | D | ||
-1 | 0 | 0 | 0 | 0 | 1 | 2 | 0 |
The table-building algorithm
The example above illustrates the general technique for assembling the table with a minimum of fuss. The principle is that of the overall search: most of the work was already done in getting to the current position, so very little needs to be done in leaving it. Here follows the algorithm; to eliminate special cases we will use the convention that is defined and its value is unequal to any possible character in .
- Set , and let have characters.
- Set , .
- If then we are done; terminate the algorithm. Otherwise, compare with .
- If they are equal, set , , and .
- If not, and if , set .
- Otherwise, set , .
- Return to step 3.
The efficiency of the table-building algorithm
The complexity of the table algorithm is , where is the length of . As except for some initialization all the work is done in step 3, it is sufficient to show that step 3 executes in time, which will be done by simultaneously examining the quantities and . In the first branch, is preserved, as both and are incremented simultaneously, but naturally, is increased. In the second branch, is replaced by , which we saw above is always strictly less than , thus increasing . In the third branch, is incremented and is not, so both and increase. Since , this means that at each stage either or a lower bound for increases; therefore since the algorithm terminates once , it must terminate after at most iterations of step 3, since begins at . Therefore the complexity of the table algorithm is .
A code example of the table-building algorithm
A C code example for the table-building algorithm is given here. As for the search algorithm, the bounds of have been incremented by 1 to make the C code more natural. The additional variable is employed to simulate the existence of . It is also assumed that both this routine and the search routine are called as subroutines of a wrapper which correctly allocates memory for .
void kmp_table(char *P) { extern int T[]; int i = 0; int j = -1; char c; c = '\0'; T[0] = j; while (P[i] != '\0') { if (P[i] == c) { T[i + 1] = j + 1; ++j; ++i; } else if (j > 0) { j = T[j]; } else { T[i + 1] = 0; ++i; j = 0; } c = T[j]; } return; }
The efficiency of the KNP algorithm
Since the two portions of the algorithm have, respectively, complexities of and , the complexity of the overall algorithm is .