Knuth-Morris-Pratt
how it works
The idea on the watch page's first example, ababc in abababcab. Then the whole method on it, step by step. A position is a letter's number in the text, from 1; a place is the position above the pattern's first letter.
Look for ababc in abababcab. First write a table from the pattern alone. A start of the pattern is its first 1, 2, 3, 4 or 5 letters. For each, write its border: the longest piece that both begins and ends that start, short of the whole start. a 0, ab 0, aba 1, abab 2, ababc 0. Writing it compares the pattern with itself, 5 comparisons. Then compare the text with the pattern from the left. a, b, a and b match; the text's a at position 5 is not c: 5 comparisons. The 4 letters matched, abab, end with their border, ab. So the pattern moves on to place 3, where its ab stands under the text's ab, and carries on at position 5. No letter that matched is read again. At place 3, a, b and c match: 3 more, and ababc stands at place 3. 5 + 5 + 3 is 13 comparisons; brute force makes 15. The code below counts places from 0 and returns them in a list, so it returns [2].
| start | a | ab | aba | abab | ababc |
|---|---|---|---|---|---|
| border | 0 | 0 | 1 | 2 | 0 |
| start | so far | compared | border | count |
|---|---|---|---|---|
| ab | 0 | b with a, differ | 0 | 1 |
| aba | 0 | a with a, match | 1 | 1 |
| abab | 1 | b with b, match | 2 | 1 |
| ababc | 2, then 0 | c with a, twice | 0 | 2 |
| place | letters above | compared | comparisons |
|---|---|---|---|
| 1 | ababa | a, b, a, b match; a is not c | 5 |
| 3 | ababc | ab lined up; a, b, c match | 3, found |
| table | 5 | ||
| all | 13 |
step 1 of 22
Look for ababc in abababcab. First write a table from the pattern alone. For each of its starts, its border is the longest piece that both begins and ends it, short of the whole start.
what it remembers to know where it is
- pattern stands at place
- 1
- letters matched here
- not yet
- border so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 7 of 22
b matches the letter after a border 1 letter long, so the first 4 letters have a border one longer: 2.
what it remembers to know where it is
- pattern stands at place
- 1
- letters matched here
- not yet
- border so far
- 1
Where it says not yet, nothing is held there at that moment.
step 9 of 22
c is not a, the letter after a border 2 letters long. Fall back to that border's own border, of nothing, and compare again.
what it remembers to know where it is
- pattern stands at place
- 1
- letters matched here
- not yet
- border so far
- 0
Where it says not yet, nothing is held there at that moment.
step 16 of 22
The text's a at position 5 is not the pattern's c.
what it remembers to know where it is
- pattern stands at place
- 1
- letters matched here
- 4
- border so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 17 of 22
4 letters matched. They end with a border 2 long, so move the pattern on to place 3, where that border stands under them, and carry on at the same text letter.
what it remembers to know where it is
- pattern stands at place
- 3
- letters matched here
- 2
- border so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 21 of 22
Every letter matched: the pattern stands at place 3. Mark it.
what it remembers to know where it is
- pattern stands at place
- 3
- letters matched here
- 5
- border so far
- not yet
Where it says not yet, nothing is held there at that moment.
step 22 of 22
The pattern no longer fits in the rest of the text. It stands at 1 place. That took 13 comparisons.
what it remembers to know where it is
- pattern stands at place
- 3
- letters matched here
- 5
- border so far
- not yet
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- the pattern's first letter alone has no border: 0Python line 9
- for each longer start, compare its last letter with the letter after the border so far; on a mismatch, fall back to that border's own border and compare againPython lines 11, 12, 13, 14, 15, 16, 17 and 18
- write how long its border isPython line 19
- while the pattern fits, compare the text letter with the pattern letter under it, moving on along both on a matchPython lines 22, 23 and 24
- every letter matched: mark a match, and move the pattern on so its border lines upPython lines 25, 26 and 27
- a mismatch: move the pattern on so the border of what matched lines up, or past the letter if nothing matchedPython lines 28, 29, 30 and 31
- the pattern no longer fits, so every match is foundPython line 32
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def knuth_morris_pratt(text, pattern):
"""Find every place a pattern stands in a text, never reading a matched
letter of the text again.
text and pattern are each a run of letters, the pattern no longer than
the text. Returns the places it stands, counted from 0.
"""
n, m = len(text), len(pattern)
border = [0] * m # each start's border; the first letter alone has none
k = 0 # the border so far
for i in range(1, m): # each start of the pattern longer than one letter
while True:
if pattern[i] == pattern[k]: # its last letter continues the border
k += 1
break
if k == 0: # no border left to fall back to
break
k = border[k - 1] # fall back to that border's own border
border[i] = k # write how long its border is
places = []
i = j = 0 # text letter i is under pattern letter j: it stands at i - j
while i - j <= n - m: # while the pattern fits
if text[i] == pattern[j]: # a match: move on along both
i, j = i + 1, j + 1
if j == m: # every letter matched
places.append(i - m) # so it stands here
j = border[m - 1] # line up the whole pattern's border
elif j > 0: # a mismatch after some letters matched
j = border[j - 1] # line up the border of what matched
else: # nothing matched
i += 1 # move on past the letter
return places # the pattern no longer fits: every match found
how it scales
The plot counts the comparisons, the table's included, on a text of letters and a pattern half as long, rounded up, in two ways. The best is b's against a's. The worst is a's ending in b against a's, and falls back at every place. Measured from 10 to 10,000.
Each mark across or up is ten times the one before. Both lines climb one mark up for each mark across: ten times the letters, ten times the comparisons. The best is 1 comparison per letter: 10 at 10, 10,000 at 10,000. The worst is about 2.5 per letter: 247 at 100, 2,497 at 1,000. Section 4 derives both.
letters compared, ten times more at each mark up
, how many letters the text has, ten times more at each mark to the right
- a text of a's and a pattern of a's ending in b, half as longsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
- a text of a's and a pattern of b's, half as longsolid where measured by running it; dashed where its formula carries it on to ten million
| letters compared | time | |
|---|---|---|
| 1,000 | 2,497 | about 2.5 microseconds |
| 100,000 | 249,997 | about 250 microseconds |
| 10,000,000 | 24,999,997 | about 25 milliseconds |
The letters compared are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count Knuth-Morris-Pratt's comparisons yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it makes a text of n
letters a and a pattern of half as many letters, rounded up, in two ways:
all b, so the table's letters all match and the search's b differs at
every place, the fewest; and a's ending in b, so the b falls back through
every border in the table and differs at every place of the search, the
most. It prints the comparisons for each, by count below, which counts
each letter of the pattern compared with another while the table is
written, and each letter of the text compared with a letter of the
pattern. The counts are the same on any computer; only the time differs.
"""
def knuth_morris_pratt(text, pattern):
"""Find every place a pattern stands in a text, never reading a matched
letter of the text again.
text and pattern are each a run of letters, the pattern no longer than
the text. Returns the places it stands, counted from 0.
"""
n, m = len(text), len(pattern)
border = [0] * m # each start's border; the first letter alone has none
k = 0 # the border so far
for i in range(1, m): # each start of the pattern longer than one letter
while True:
if pattern[i] == pattern[k]: # its last letter continues the border
k += 1
break
if k == 0: # no border left to fall back to
break
k = border[k - 1] # fall back to that border's own border
border[i] = k # write how long its border is
places = []
i = j = 0 # text letter i is under pattern letter j: it stands at i - j
while i - j <= n - m: # while the pattern fits
if text[i] == pattern[j]: # a match: move on along both
i, j = i + 1, j + 1
if j == m: # every letter matched
places.append(i - m) # so it stands here
j = border[m - 1] # line up the whole pattern's border
elif j > 0: # a mismatch after some letters matched
j = border[j - 1] # line up the border of what matched
else: # nothing matched
i += 1 # move on past the letter
return places # the pattern no longer fits: every match found
def count(text, pattern):
"""How many comparisons knuth_morris_pratt makes: one for each letter of
the pattern compared with another in the table, and one for each letter
of the text compared with a letter of the pattern."""
n, m = len(text), len(pattern)
border = [0] * m
compared = 0
k = 0
for i in range(1, m):
while True:
compared += 1
if pattern[i] == pattern[k]:
k += 1
break
if k == 0:
break
k = border[k - 1]
border[i] = k
i = j = 0
while i - j <= n - m:
compared += 1
if text[i] == pattern[j]:
i, j = i + 1, j + 1
if j == m:
j = border[m - 1]
elif j > 0:
j = border[j - 1]
else:
i += 1
return compared
def cheapest(n):
"""A text of n a's and a pattern of half as many b's, rounded up."""
return "a" * n, "b" * ((n + 1) // 2)
def dearest(n):
"""A text of n a's and a pattern of half as many letters, rounded up,
all a but the last, which is b."""
return "a" * n, "a" * ((n + 1) // 2 - 1) + "b"
if __name__ == "__main__":
print(f"{'n':>7} {'all b':>8} {'a then b':>10}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000):
print(f"{n:>7} {count(*cheapest(n)):>8} {count(*dearest(n)):>10}")
best, worst and average
Here best and worst are texts and patterns of the same lengths, letters and , half of rounded up, as on brute force's page. Both grow in step with the text. For 6 letters and 3, the best makes 6 comparisons and the worst 12. No average is worked out.
A case is one kind of text and pattern. A bound says how fast its cost grows as letters are added.
The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. Here both growing pieces grow as the text does, and the 3 stays put: at 10,000 letters the worst is 20,000, plus 5,000, less 3, which is 24,997. So both cases have the same bound, , and only the fixed multiple tells them apart.
| besta text of a's and a pattern of b's, half as long | worsta text of a's and a pattern of a's ending in b, half as long | |
|---|---|---|
| letters compared | , from 3 letters on | |
| how the letters compared grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: a border for each letter of the pattern, and the place, beside the places found
Extra memory is the room it needs on top of the input itself, while it runs.
| text | pattern | table | search | in all |
|---|---|---|---|---|
| abababcab | ababc | 5 | 8 | 13 |
| abababab | abab | 3 | 8 | 11 |
| everything | zoo | 2 | 8 | 10 |
| aaaaaaaaaa | aaaaab | 9 | 14 | 23 |
| ababaab | abaa | 4 | 7 | 11 |
| n | best | worst |
|---|---|---|
| 6 | 6 | 12 |
| 7 | 7 | 15 |
| 10 | 10 | 22 |
| pattern | comparisons |
|---|---|
| b | 6 |
| ab | 11 |
| aab | 12 |
| aaab | 13 |
| aaaab | 14 |
| aaaaab | 15 |
where the formula comes from
Question 1 counts the fewest comparisons and question 2 the most, the plot's two lines. Question 3 shows that no text and pattern of these lengths cost more than question 2's, and which pattern length costs the most.
the move: the table for b's
the line:start b bb bbb border 0 1 2 The table for bbb. Each b after the first matches at once: 2 comparisons. why it is allowed: Each start longer than one letter ends in b, which matches the b after the border so far at once: 1 comparison each, and the border grows by 1. There are such starts. For bbb, 2.
the move: one comparison a place
the line:why it is allowed: The text's a against the pattern's first letter, b, differs. Nothing matched, so the pattern moves on 1 place.
guess it, thenthe move: the places
the line:why it is allowed: From place 1, one place at a time by line 2, to the last. There the pattern's letters end under letter , so the last place is . For 6 letters and 3, places 1 to 4.
guess it, thenthe move: add the two
the line:why it is allowed: Line 1's , and 1 at each of line 3's places, by line 2, added; the 's cancel. For 6, 2 + 4, which is 6.
guess it, thenthe move: no search costs less
the line:why it is allowed: The table compares at least once for each of the starts longer than one letter. In the search the text letter, the one being compared, starts at 1 and moves on at most 1 a comparison. It is never left of the place, and the search stops only once the place passes . So it has moved on at least times, and the search compared at least that often. and added are , line 4's . For 6 letters and 3, the place must reach 5, so the text letter moves on at least 4 times: 2 + 4, which is 6.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4, is .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4 again.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 8, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 7 and 9 bound by the same growth, the text's.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: the table's a's
the line:why it is allowed: Each of the starts from 2 letters to ends in a, which matches the a after the border so far at once. That is 1 comparison each, and the border grows by 1. So a run of a's has a border 1 shorter than itself. For aab, 1.
the move: the table's b
the line:start a aa aab border 0 1 0 The table for aab. aa costs 1; aab's b differs from a after borders 1 and 0, 2 more. why it is allowed: The last start's b differs from the a after a border of . It falls back 1 letter at a time, by line 1, to a border of nothing, and differs at each: borders down to 0, comparisons. For aab, 2.
guess it, thenthe move: the table
the line:why it is allowed: Lines 1 and 2 added. For aab, 3.
guess it, thenthe move: the first place
the line:why it is allowed: The pattern's a's match the text's, then its b differs from an a.
guess it, thenthe move: each place after
the line:place letters above comparisons 1 aaa 3 2 aaa 2 3 aaa 2 4 aaa 2 search 9 A text of 6 a's and aab. 3 at place 1, then 2 at each place after. With the table's 3, 12. why it is allowed: The a's matched end with a border of a's, by line 1. So the pattern moves on 1 place and carries on at the same text letter, where its last a matches; then its b differs from the next a.
guess it, thenthe move: the places
the line:why it is allowed: One place at a time, by line 5. At the last place the pattern's letters end under letter , so the last place is . For 6 letters and 3, places 1 to 4.
guess it, thenthe move: the search
the line:why it is allowed: Line 4's , then 2 at each place after place 1, by line 5. Line 6's places less place 1 are . For 6, 3 + 2 times 3.
guess it, thenthe move: multiply out
the line:why it is allowed: Twice all of is twice less twice . Adding line 7's gives one back: . For 6, 12 - 3, which is 9.
guess it, thenthe move: add the two
the line:why it is allowed: Lines 3 and 8 added: and . For 6, 3 + 9, which is 12.
guess it, thenthe move: the pattern half the text
the line:why it is allowed: Line 9 with as half of rounded up. For 6, 12 + 3 - 3, which is 12; for 7, 14 + 4 - 3, which is 15.
guess it, thenthe move: a ceiling
the line:why it is allowed: Half of rounded up is at most , so line 10 is at most , less than . For 6, 12 against 18.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 11, with the fixed multiple 3.
guess it, thenthe move: a floor
the line:why it is allowed: From 3 up, half of rounded up is at least 2. So line 10 is at least 1 less than twice , and that is at least . For 6, 12 against 6.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 13, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 12 and 14 bound by the same growth, the text's.
guess it, then
try it with a small : at , line 10 gives , which you can work out by hand
the move: what a table comparison does
the line:why it is allowed: One that matches, or differs when the border so far is already 0, settles its start: one for each start of 2 letters or more, . One that differs with a border left falls back to a shorter border.
the move: a ceiling for the table
the line:start aa aaa aaab border after 1 2 0 comparisons 1 1 3 settling 1 1 1 shortenings 0 0 2 The table for aaab. The border grows twice, so it can shorten only twice. 3 settling comparisons and 2 shortenings, 5, which is 2 times 4 - 3. why it is allowed: The starts settled before the last each add at most 1 to the border so far. Each shortening takes off at least 1, and it never goes below 0: at most shortenings. Line 1's settling comparisons plus these, . For aaab, 3 + 2, which is 5.
guess it, thenthe move: what a search comparison does
the line:why it is allowed: A match moves on the text letter. A mismatch with nothing matched moves on both. A mismatch after some letters matched keeps the text letter and moves the place on, to where their border lines up. Neither ever moves back.
guess it, thenthe move: a ceiling for the search
the line:comparison text letter's position place 1 1 1 2 2 1 3 3 1 4 3 2 5 4 2 6 4 3 7 5 3 8 5 4 9 6 4 The search of 6 a's for aab. Each comparison moves one on, 5 + 3 moves, then the last, 9. why it is allowed: Up to the last comparison, the text letter goes from 1 to at most , at most moves. The place goes from 1 to at most , at most . By line 3 each comparison before the last makes at least one move, so there are at most that many before it. With the last, . For 6 letters and 3, 5 + 3 + 1, which is 9.
guess it, thenthe move: no search costs more
the line:m table at most search at most in all 2 1 10 11 3 3 9 12 4 5 8 13 5 7 7 14 6 9 6 15 A text of 6 letters and each pattern length. a's ending in b cost exactly the in-all figure in every row, as section 3's last table shows. why it is allowed: Lines 2 and 4 added, for any text of letters and pattern of letters, at least 2. Question 2's lines 1 to 9 hold for any ; only line 10 makes it half of . So a's ending in b against a's count exactly this many at every : none costs more. For 6 letters and 3, 12.
guess it, thenthe move: the most at half the text
the line:why it is allowed: Line 5 with as half of rounded up, question 2's . For 6, 12.
guess it, thenthe move: the dearest length
the line:why it is allowed: Line 5 grows with , so among patterns of 2 letters or more the dearest is as long as the text, with as . Question 2's line 9 with as counts exactly that, 15 for 6 letters. A pattern of 1 letter has no table and compares each text letter once, , which is less.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
count it yourself
A text of 6 a's and the pattern aab, question 2's worst at 6. The table costs 3, then the search 3 at place 1 and 2 at each place after. A position is a letter's number in the text, from 1.
| step | the row | what happens | letters compared |
|---|---|---|---|
| 1 | Look for aab in aaaaaa. First write a table from the pattern alone. For each of its starts, its border is the longest piece that both begins and ends it, short of the whole start. | 0 | |
| 2 | 0 | The first letter, a, alone has no border: write 0.0 | 0 |
| 3 | 0 | a matches the letter after a border of nothing, so the first 2 letters have a border one longer: 1.0 | 1 |
| 4 | 0, 1 | Write it: the first 2 letters have a border 1 letter long.0, 1 | 1 |
| 5 | 0, 1 | b is not a, the letter after a border 1 letter long. Fall back to that border's own border, of nothing, and compare again.0, 1 | 2 |
| 6 | 0, 1 | b is not a, the first letter, and there is no shorter border left to fall back to.0, 1 | 3 |
| 7 | 0, 1, 0 | Write it: the first 3 letters have a border of nothing.0, 1, 0 | 3 |
| 8 | 0, 1, 0 | The text's a at position 1 matches the pattern's a.0, 1, 0 | 4 |
| 9 | 0, 1, 0 | The text's a at position 2 matches the pattern's a.0, 1, 0 | 5 |
| 10 | 0, 1, 0 | The text's a at position 3 is not the pattern's b.0, 1, 0 | 6 |
| 11 | 0, 1, 0 | 2 letters matched. They end with a border 1 long, so move the pattern on to place 2, where that border stands under them, and carry on at the same text letter.0, 1, 0 | 6 |
| 12 | 0, 1, 0 | The text's a at position 3 matches the pattern's a.0, 1, 0 | 7 |
| 13 | 0, 1, 0 | The text's a at position 4 is not the pattern's b.0, 1, 0 | 8 |
| 14 | 0, 1, 0 | 2 letters matched. They end with a border 1 long, so move the pattern on to place 3, where that border stands under them, and carry on at the same text letter.0, 1, 0 | 8 |
| 15 | 0, 1, 0 | The text's a at position 4 matches the pattern's a.0, 1, 0 | 9 |
| 16 | 0, 1, 0 | The text's a at position 5 is not the pattern's b.0, 1, 0 | 10 |
| 17 | 0, 1, 0 | 2 letters matched. They end with a border 1 long, so move the pattern on to place 4, where that border stands under them, and carry on at the same text letter.0, 1, 0 | 10 |
| 18 | 0, 1, 0 | The text's a at position 5 matches the pattern's a.0, 1, 0 | 11 |
| 19 | 0, 1, 0 | The text's a at position 6 is not the pattern's b.0, 1, 0 | 12 |
| 20 | 0, 1, 0 | The pattern no longer fits in the rest of the text. It stands nowhere in the text. That took 12 comparisons.0, 1, 0 | 12 |
In all, 12 letters compared. The formula from section 4, , gives at : the same.
where you meet it
Three people worked this search out around 1970, and its table spread to searching for many words at once.
The 1977 paper
Knuth, Morris and Pratt published the method together in 1977. Morris had found it on his own in 1969, while writing a text editor; Knuth found it apart from him in 1970.
source: D. E. Knuth, J. H. Morris and V. R. Pratt, SIAM Journal on Computing 6(2), 1977, pages 323 to 350, Fast pattern matching in strings (opens in a new tab)
Many words at once
Aho and Corasick's 1975 paper builds the same kind of table for a whole list of words, searched in one pass, for finding citations in a library's citation index.
source: A. V. Aho and M. J. Corasick, Communications of the ACM 18(6), 1975, pages 333 to 340, Efficient string matching: an aid to bibliographic search (opens in a new tab)
The books' count
The books count the search's comparisons in two kinds. Those that move the text letter on number at most . Those that shorten the letters matched so far come no more often than they grew. They grow by 1 only when two letters match, which moves the text letter on, so at most times. So at most , whatever the text.
source: the books' volume four, chapter 41
what is used instead
On ordinary words Horspool can read far fewer letters: 6 against 14, its table included, on toothpaste and paste. Brute force needs no table, and makes 10 there.
how it compares
The four searches on Horspool's first example, and on 10 a's and aaaab. Knuth-Morris-Pratt never reads a matched letter again, but pays for its table.
| method | comparisons | also |
|---|---|---|
| brute force | 10 | |
| Horspool | 6 | |
| Knuth-Morris-Pratt | 14 | its table's 4 included |
| Rabin-Karp | 6 | 7 fingerprints |
| method | comparisons | also |
|---|---|---|
| brute force | 30 | |
| Horspool | 6 | |
| Knuth-Morris-Pratt | 22 | its table's 7 included |
| Rabin-Karp | 0 | 7 fingerprints |