Knuth–Morris–Pratt algorithm
In computer science, the Knuth–Morris–Pratt string-searching algorithm searches for occurrences of a "word"
W
within a main "text string" S
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 indexm
in string S
that matches the search word W
.The most straightforward algorithm, known as the "Brute-force" or "Naive" algorithm, is to look for a word match at each index
m
, the position in the string being searched, i.e. S
. At each position m
the algorithm first checks for equality of the first character in the word being searched, i.e. S =? W
. 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, i
. The algorithm retrieves the character W
in the word being searched and checks for equality of the expression S =? W
. If all successive characters match in W
at position m
, then a match is found at that position in the search string. If the index m
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 262. So if the characters are random, then the expected complexity of searching string
S
of length n is on the order of n comparisons or O. The expected performance is very good. If S
is 1 million characters and W
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
m
may take many character comparisons. The worst case is if the two strings match in all but the last letter. Imagine that the string S
consists of 1 million characters that are all A, and that the word W
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 W
is k, then the worst-case performance is O.The KMP algorithm has a better worst-case performance than the straightforward algorithm. KMP spends a little time precomputing a table, and then it uses that table to do an efficient search of the string in O.
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 because
S ≠ W
, it will increment m
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. Advancing the trial match position m
by one throws away the first A, so KMP knows there are 998 A characters that match W
and does not retest them; that is, KMP sets i
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 and where it will resume testing.KMP algorithm
Example of the search algorithm
To illustrate the algorithm's details, consider a run of the algorithm, whereW
= "ABCDABD" and S
= "ABC ABCDAB ABCDABCDABDE". At any given time, the algorithm is in a state determined by two integers:-
m
, denoting the position withinS
where the prospective match forW
begins, -
i
, denoting the index of the currently considered character inW
.
S
with W
and increments i
if they are equal. This is depicted, at the start of the run, like1 2
m: 01234567890123456789012
S:
W:
i:
The algorithm compares successive characters of
W
to "parallel" characters of S
, moving from one to the next by incrementing i
if they match. However, in the fourth step S = ' '
does not match W = 'D'
. Rather than beginning to search again at S
, we note that no 'A'
occurs between positions 1 and 2 in S
; hence, having checked all those characters previously, there is no chance of finding the beginning of a match. Therefore, the algorithm sets m = 3
and i = 0
.1 2
m: 01234567890123456789012
S: ABC
W:
i:
This match fails at the initial character, so the algorithm sets
m = 4
and i = 0
1 2
m: 01234567890123456789012
S: ABC
W:
i:
Here,
i
increments through a nearly complete match "ABCDAB"
until i = 6
giving a mismatch at W
and S
. However, just prior to the end of the current partial match, there was that substring "AB"
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 m = 8
and i = 2
and continues matching. Thus the algorithm not only omits previously matched characters of S
, but also previously matched characters of W
.1 2
m: 01234567890123456789012
S: ABC ABCD
W:
i:
This search at the new position fails immediately because
W
does not match S
. As in the first trial, the mismatch causes the algorithm to return to the beginning of W
and begins searching at the mismatched character position of S
: m = 10
, reset i = 0
.1 2
m: 01234567890123456789012
S: ABC ABCDAB
W:
i:
The match at
m=10
fails immediately, so the algorithm next tries m = 11
and i = 0
.1 2
m: 01234567890123456789012
S: ABC ABCDAB
W:
i:
Once again, the algorithm matches
"ABCDAB"
, but the next character, 'C'
, does not match the final character 'D'
of the word W
. Reasoning as before, the algorithm sets m = 15
, to start at the two-character string "AB"
leading up to the current position, set i = 2
, and continue matching from the current position.1 2
m: 01234567890123456789012
S: ABC ABCDAB ABCD
W:
i:
This time the match is complete, and the first character of the match is
S
.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" tableT
, 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. The entries of T
are constructed so that if we have a match starting at S
that fails when comparing S
to W
, then the next possible match will start at index m + i - T
in S
. This has two implications: first, T = -1
, which indicates that if W
is a mismatch, we cannot backtrack and must simply check the next character; and second, although the next possible match will begin at index m + i - T
, as in the example above, we need not actually check any of the T
characters after that, so that we continue searching from W = S then
let j ← j + 1
let k ← k + 1
if k = length then
let P ← j - k, nP ← nP + 1
let k ← T
else
let k ← T
if k < 0 then
let j ← j + 1
let k ← k + 1Efficiency of the search algorithm
Assuming the prior existence of the table T
, the search portion of the Knuth–Morris–Pratt algorithm has complexity O, where n is the length of S
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 while
loop. To bound the number of iterations of this loop; observe that T
is constructed so that if a match which had begun at S
fails while comparing S
to W
, then the next possible match must begin at S
. In particular, the next possible match must occur at a higher index than m
, so that T < i
.
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 i
and does not change m
, so that the index m + i
of the currently scrutinized character of S
is increased. The second branch adds i - T
to m
, and as we have seen, this is always a positive number. Thus the location m
of the beginning of the current potential match is increased. At the same time, the second branch leaves m + i
unchanged, for m
gets i - T
added to it, and immediately after T
gets assigned as the new value of i
, hence new_m + new_i = old_m + old_i - T + T = old_m + old_i
. Now, the loop ends if m + i
= n; therefore, each branch of the loop can be reached at most n times, since they respectively increase either m + i
or m
, and m ≤ m + i
: if m
= n, then certainly m + i
≥ n, so that since it increases by unit increments at most, we must have had m + i
= 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.
Here is another way to think about the runtime:
Let us say we begin to match W
and S
at position i
and p
. If W
exists as a substring of S
at p, then W = S
.
Upon success, that is, the word and the text matched at the positions, we increase i
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, and we attempt to match W
.
The maximum number of roll-back of i
is bounded by i
, 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 S
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 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 W
, the length of the longest possible initial segment of W
leading up to that position, other than the full segment starting at W
that just failed to match; this is how far we have to backtrack in finding the next match. Hence T
is exactly the length of the longest possible proper initial segment of W
which is also a segment of the substring ending at W
. 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, we set T = -1
, as discussed below.Working example of the table-building algorithm
We consider the example of W = "ABCDABD"
first. We will see that it follows much the same pattern as the main search, and is efficient for similar reasons. We set T = -1
. To find T
, we must discover a proper suffix of "A"
which is also a prefix of pattern W
. But there are no proper suffixes of "A"
, so we set T = 0
. To find T
, we see that the substring W
- W
has a proper suffix "B"
. However "B" is not a prefix of the pattern W
. Therefore, we set T = 0
.
Continuing to T
, 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 and ending at W
with length 2 ; then its first character is also a proper prefix of W
, hence a proper prefix itself, and it ends at W
, which we already determined did not occur as T = 0
and not T = 1
. 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 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 T = 0
.
We pass to the subsequent W
, 'A'
. 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 W
. But instead of setting T = 0
, we can do better by noting that W = W
, and also that a look-up of T
implies the corresponding S
character, S
, was a mismatch and therefore S ≠ 'A'
. Thus there is no point in restarting the search at S
; we should begin at 1 position ahead. This means that we may shift pattern W
by match length plus one character, so T = -1
.
Considering now the next character, W
, which is 'B'
: though by inspection the longest substring would appear to be 'A'
, we still set T = 0
. The reasoning is similar to why T = -1
. W
itself extends the prefix match begun with W
, and we can assume that the corresponding character in S
, S ≠ 'B'
. So backtracking before W
is pointless, but S
may be 'A'
, hence T = 0
.
Finally, we see that the next character in the ongoing segment starting at W = 'A'
would be 'B'
, and indeed this is also W
. Furthermore, the same argument as above shows that we need not look before W
to find a segment for W
, so that this is it, and we take T = 2
.
Therefore, we compile the following table:
i
0 1 2 3 4 5 6 7 W
A B C D A B D T
-1 0 0 0 -1 0 2 0
Another example:
i
0 1 2 3 4 5 6 7 8 9 W
A B A C A B A B C T
-1 0 -1 1 -1 0 -1 3 2 0
Another example :
i
0 1 2 3 4 5 6 7 8 9 W
A B A C A B A B A T
-1 0 -1 1 -1 0 -1 3 -1 3
Another more complicated example:
i
00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 W
P A R T I C I P A T E I N P A R A C H U T E T
-1 0 0 0 0 0 0 -1 0 2 0 0 0 0 0 -1 0 0 3 0 0 0 0 0 0
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
output:
an array of integers, T
define variables:
an integer, pos ← 1
an integer, cnd ← 0
let T ← -1
while pos < length do
if W = W then
let T ← T
else
let T ← cnd
let cnd ← T
while cnd ≥ 0 and W <> W do
let cnd ← T
let pos ← pos + 1, cnd ← cnd + 1
let T ← cndEfficiency of the table-building algorithm
The complexity of the table algorithm is O
, where k
is the length of W
. This is easy to prove, pos
is initialized as 1, and the loop condition is pos < k
. pos
is increased by 1 every iteration of the loop, thus the loop will take k - 1
iterations, which corresponds to an algorithmic efficiency of O
using the Big O notation.Efficiency of the KMP algorithm
Since the two portions of the algorithm have, respectively, complexities of O
and O
, the complexity of the overall algorithm is O
.
These complexities are the same, no matter how many repetitive patterns are in W
or S
.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 in the text, the failure function table for character is consulted for the index in the pattern at which the mismatch took place. This will return the length of the longest substring ending at matching a prefix of the pattern, with the added condition that the character after the prefix is. With this restriction, character 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.
The 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.