Knuth–Morris–Pratt algorithm

In computer science, the Knuth–Morris–Pratt algorithm (or KMP algorithm) is a string-searching algorithm that searches for occurrences of a "word"  within a main "text string"   by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing re-examination of previously matched characters.

The algorithm was conceived by James H. Morris and independently discovered by Donald Knuth "a few weeks later" from automata theory. Morris and Vaughan Pratt published a technical report in 1970. The three also published the algorithm jointly in 1977. Independently, in 1969, Matiyasevich discovered a similar algorithm, coded by a two-dimensional Turing machine, while studying a string-pattern-matching recognition problem over a binary alphabet. This was the first linear-time algorithm for string matching.

Background
A string-matching algorithm wants to find the starting index  in string   that matches the search word.

The most straightforward algorithm, known as the "brute-force" or "naive" algorithm, is to look for a word match at each index, i.e. the position in the string being searched that corresponds to the character. At each position  the algorithm first checks for equality of the first character in the word being searched, i.e.  . If a match is found, the algorithm tests the other characters in the word being searched by checking successive values of the word position index,. The algorithm retrieves the character  in the word being searched and checks for equality of the expression. If all successive characters match in  at position , then a match is found at that position in the search string. If the index  reaches the end of the string then there is no match, in which case the search is said to "fail".

Usually, the trial check will quickly reject the trial match. If the strings are uniformly distributed random letters, then the chance that characters match is 1 in 26. In most cases, the trial check will reject the match at the initial letter. The chance that the first two letters will match is 1 in 26 (1 in 26^2 chances of a match over 26 possible letters). So if the characters are random, then the expected complexity of searching string  of length n is on the order of n comparisons or O(n). The expected performance is very good. If  is 1 million characters and   is 1000 characters, then the string search should complete after about 1.04 million character comparisons.

That expected performance is not guaranteed. If the strings are not random, then checking a trial  may take many character comparisons. The worst case is if the two strings match in all but the last letter. Imagine that the string  consists of 1 million characters that are all A, and that the word   is 999 A characters terminating in a final B character. The simple string-matching algorithm will now examine 1000 characters at each trial position before rejecting the match and advancing the trial position. The simple string search example would now take about 1000 character comparisons times 1 million positions for 1 billion character comparisons. If the length of  is k, then the worst-case performance is O(k&sdot;n).

The KMP algorithm has a better worst-case performance than the straightforward algorithm. KMP spends a little time precomputing a table (on the order of the size of, O(k)), and then it uses that table to do an efficient search of the string in O(n).

The difference is that KMP makes use of previous match information that the straightforward algorithm does not. In the example above, when KMP sees a trial match fail on the 1000th character ( = 999) because , it will increment   by 1, but it will know that the first 998 characters at the new position already match. KMP matched 999 A characters before discovering a mismatch at the 1000th character (position 999). Advancing the trial match position  by one throws away the first A, so KMP knows there are 998 A characters that match   and does not retest them; that is, KMP sets   to 998. KMP maintains its knowledge in the precomputed table and two state variables. When KMP discovers a mismatch, the table determines how much KMP will increase (variable ) and where it will resume testing (variable  ).

Example of the search algorithm
To illustrate the algorithm's details, consider a (relatively artificial) run of the algorithm, where  = "ABCDABD" and   = "ABC ABCDAB ABCDABCDABDE". At any given time, the algorithm is in a state determined by two integers:


 * , denoting the position within  where the prospective match for   begins,
 * , denoting the index of the currently considered character in.

In each step the algorithm compares  with   and increments   if they are equal. This is depicted, at the start of the run, like

1        2   m: 01234567890123456789012 S: ABCABCDAB ABCDABCDABDE W: ABCDABD i: 0123456

The algorithm compares successive characters of  to "parallel" characters of , moving from one to the next by incrementing   if they match. However, in the fourth step  does not match. Rather than beginning to search again at, we note that no   occurs between positions 1 and 2 in  ; hence, having checked all those characters previously (and knowing they matched the corresponding characters in  ), there is no chance of finding the beginning of a match. Therefore, the algorithm sets  and.

1        2   m: 01234567890123456789012 S: ABCABCDAB ABCDABCDABDE W:   ABCDABD i:   0123456

This match fails at the initial character, so the algorithm sets  and

1        2   m: 01234567890123456789012 S: ABC ABCDABABCDABCDABDE W:    ABCDABD i:    0123456

Here,  increments through a nearly complete match   until   giving a mismatch at   and. However, just prior to the end of the current partial match, there was that substring  that could be the beginning of a new match, so the algorithm must take this into consideration. As these characters match the two characters prior to the current position, those characters need not be checked again; the algorithm sets  (the start of the initial prefix) and   (signaling the first two characters match) and continues matching. Thus the algorithm not only omits previously matched characters of  (the  ), but also previously matched characters of   (the prefix  ).

1        2   m: 01234567890123456789012 S: ABC ABCDABABCDABCDABDE W:        ABCDABD i:        0123456

This search at the new position fails immediately because  (a  ) does not match   (a  ). As in the first trial, the mismatch causes the algorithm to return to the beginning of  and begins searching at the mismatched character position of  : , reset.

1        2   m: 01234567890123456789012 S: ABC ABCDABABCDABCDABDE W:          ABCDABD i:          0123456

The match at  fails immediately, so the algorithm next tries   and.

1        2   m: 01234567890123456789012 S: ABC ABCDAB ABCDABCDABDE W:           ABCDABD i:           0123456

Once again, the algorithm matches, but the next character,  , does not match the final character   of the word. Reasoning as before, the algorithm sets, to start at the two-character string   leading up to the current position, set  , and continue matching from the current position.

1        2   m: 01234567890123456789012 S: ABC ABCDAB ABCDABCDABDE W:               ABCDABD i:               0123456

This time the match is complete, and the first character of the match is.

Description of pseudocode for the search algorithm
The above example contains all the elements of the algorithm. For the moment, 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 when a mismatch is found. The entries of  are constructed so that if we have a match starting at   that fails when comparing   to , then the next possible match will start at index   in   (that is,   is the amount of "backtracking" we need to do after a mismatch). This has two implications: first,, which indicates that if   is a mismatch, we cannot backtrack and must simply check the next character; and second, although the next possible match will begin at index  , as in the example above, we need not actually check any of the   characters after that, so that we continue searching from. The following is a sample pseudocode implementation of the KMP search algorithm. algorithm kmp_search: input: an array of characters, S (the text to be searched) an array of characters, W (the word sought) output: an array of integers, P (positions in S at which W is found) an integer, nP (number of positions) define variables: an integer, j ← 0 (the position of the current character in S)        an integer, k ← 0 (the position of the current character in W)         an array of integers, T (the table, computed elsewhere) let nP ← 0 while j < length(S) do if W[k] = S[j] then let j ← j + 1 let k ← k + 1 if k = length(W) then (occurrence found, if only first occurrence is needed, m ← j - k may be returned here) let P[nP] ← j - k, nP ← nP + 1 let k ← T[k] (T[length(W)] can't be -1) else let k ← T[k] if k < 0 then let j ← j + 1 let k ← k + 1

Efficiency of the search algorithm
Assuming the prior existence of the table, the search portion of the Knuth–Morris–Pratt algorithm has complexity O(n), where n is the length of   and the O is big-O notation. Except for the fixed overhead incurred in entering and exiting the function, all the computations are performed in the  loop. To bound the number of iterations of this loop; observe that  is constructed so that if a match which had begun at   fails while comparing   to , then the next possible match must begin at. In particular, the next possible match must occur at a higher index than, so that.

This fact implies that the loop can execute at most 2n times, since at each iteration it executes one of the two branches in the loop. The first branch invariably increases  and does not change , so that the index   of the currently scrutinized character of   is increased. The second branch adds  to , and as we have seen, this is always a positive number. Thus the location  of the beginning of the current potential match is increased. At the same time, the second branch leaves  unchanged, for   gets   added to it, and immediately after   gets assigned as the new value of , hence. Now, the loop ends if  = n; therefore, each branch of the loop can be reached at most n times, since they respectively increase either   or , and  : if   = n, then certainly   ≥ n, so that since it increases by unit increments at most, we must have had   = n at some point in the past, and therefore either way we would be done.

Thus the loop executes at most 2n times, showing that the time complexity of the search algorithm is O(n).

Here is another way to think about the runtime: Let us say we begin to match  and   at position   and. If  exists as a substring of   at p, then. Upon success, that is, the word and the text matched at the positions, we increase  by 1. Upon failure, that is, the word and the text do not match at the positions, the text pointer is kept still, while the word pointer is rolled back a certain amount ( , where  is the jump table), and we attempt to match   with. The maximum number of roll-back of  is bounded by , that is to say, for any failure, we can only roll back as much as we have progressed up to the failure. Then it is clear the runtime is 2n.

"Partial match" table (also known as "failure function")
The goal of the table is to allow the algorithm not to match any character of  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 position in, the length of the longest possible initial segment of   leading up to (but not including) that position, other than the full segment starting at   that just failed to match; this is how far we have to backtrack in finding the next match. Hence  is exactly the length of the longest possible proper initial segment of   which is also a 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 below.

Working example of the table-building algorithm
We consider the example of  first. We will see that it follows much the same pattern as the main search, and is efficient for similar reasons. We set. To find, we must discover a proper suffix of   which is also a prefix of pattern. But there are no proper suffixes of, so we set. To find, we see that the substring   -    has a proper suffix. However "B" is not a prefix of the pattern. Therefore, we set.

Continuing to, we first check the proper suffix of length 1, and as in the previous case it fails. Should we also check longer suffixes? No, we now note that there is a shortcut to checking all suffixes: let us say that we discovered a proper suffix which is a proper prefix (a proper prefix of a string is not equal to the string itself) and ending at  with length 2 (the maximum possible); then its first character is also a proper prefix of , hence a proper prefix itself, and it ends at  , which we already determined did not occur as   and not. Hence at each stage, the shortcut rule is that one needs to consider checking suffixes of a given size m+1 only if a valid suffix of size m was found at the previous stage (i.e. ) and should not bother to check m+2, m+3, etc.

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.

We pass to the subsequent,. The same logic shows that the longest substring we need to consider has length 1, and as in the previous case it fails since "D" is not a prefix of. But instead of setting, we can do better by noting that  , and also that a look-up of   implies the corresponding   character,  , was a mismatch and therefore. Thus there is no point in restarting the search at ; we should begin at 1 position ahead. This means that we may shift pattern  by match length plus one character, so.

Considering now the next character,, which is  : though by inspection the longest substring would appear to be  , we still set. The reasoning is similar to why. itself extends the prefix match begun with, and we can assume that the corresponding character in  ,. So backtracking before  is pointless, but   may be , hence.

Finally, we see that the next character in the ongoing segment starting at  would be , and indeed this is also. Furthermore, the same argument as above shows that we need not look before  to find a segment for , so that this is it, and we take.

Therefore, we compile the following table:

Another example:

Another example (slightly changed from the previous example):

Another more complicated example:

Description of pseudocode for 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. The only minor complication is that the logic which is correct late in the string erroneously gives non-proper substrings at the beginning. This necessitates some initialization code. algorithm kmp_table: input: an array of characters, W (the word to be analyzed) output: an array of integers, T (the table to be filled) define variables: an integer, pos ← 1 (the current position we are computing in T)        an integer, cnd ← 0 (the zero-based index in W of the next character of the current candidate substring) let T[0] ← -1 while pos < length(W) do if W[pos] = W[cnd] then let T[pos] ← T[cnd] else let T[pos] ← cnd while cnd ≥ 0 and W[pos] ≠ W[cnd] do let cnd ← T[cnd] let pos ← pos + 1, cnd ← cnd + 1 let T[pos] ← cnd (only needed when all word occurrences are searched)

Efficiency of the table-building algorithm
The time (and space) complexity of the table algorithm is $$O(k)$$, where $$k$$ is the length of.


 * The outer loop:  is initialized to 1, the loop condition is , and   is increased by 1 in every iteration of the loop. Thus the loop will take $$k - 1$$ iterations.


 * The inner loop:  is initialized to   and gets increased by at most 1 in each outer loop iteration.   is always less than , so   gets decreased by at least 1 in each inner loop iteration; the inner loop condition is  . This means that the inner loop can execute at most as many times in total, as the outer loop has executed – each decrease of   by 1 in the inner loop needs to have a corresponding increase by 1 in the outer loop. Since the outer loop takes $$k - 1$$ iterations, the inner loop can take no more than $$k - 1$$ iterations in total.

Combined, the outer and inner loops take at most $$2k-2$$ iterations. This corresponds to $$O(k)$$ time complexity using the Big O notation.

Efficiency of the KMP algorithm
Since the two portions of the algorithm have, respectively, complexities of  and , the complexity of the overall algorithm is.

These complexities are the same, no matter how many repetitive patterns are in  or.

Variants
A real-time version of KMP can be implemented using a separate failure function table for each character in the alphabet. If a mismatch occurs on character $$x$$ in the text, the failure function table for character $$x$$ is consulted for the index $$i$$ in the pattern at which the mismatch took place. This will return the length of the longest substring ending at $$i$$ matching a prefix of the pattern, with the added condition that the character after the prefix is $$x$$. With this restriction, character $$x$$ in the text need not be checked again in the next phase, and so only a constant number of operations are executed between the processing of each index of the text. This satisfies the real-time computing restriction.

Booth's algorithm uses a modified version of the KMP preprocessing function to find the lexicographically minimal string rotation. The failure function is progressively calculated as the string is rotated.