Skip to content

Knuth-Morris-Pratt

words

Level 3 of 3

Also called KMP algorithm and Knuth-Morris-Pratt algorithm.

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].

startaababaababababc
border00120
The table for ababc. aba begins and ends with a, and abab with ab; ababc ends in c, which begins nothing.
startso farcomparedbordercount
ab0b with a, differ01
aba0a with a, match11
abab1b with b, match21
ababc2, then 0c with a, twice02
Writing the table for ababc. Each start's last letter is compared with the letter after the border so far. 5 comparisons.
placeletters abovecomparedcomparisons
1ababaa, b, a, b match; a is not c5
3ababcab lined up; a, b, c match3, found
table5
all13
ababc tried at 2 places of abababcab, found at place 3. Place 2 is skipped, and the text's ab at positions 3 and 4 is not read again.
A mismatch that keeps a border: 7 moments of its 22 steps, the steps between them left for the watch page
  1. step 1 of 22

    abababcabababcababc

    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.

    watch from here

  2. step 7 of 22

    abababcabababcababc001

    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.

    watch from here

  3. step 9 of 22

    abababcabababcababc0012

    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.

    watch from here

  4. step 16 of 22

    abababcabababcababc00120

    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.

    watch from here

  5. step 17 of 22

    abababcabababcababc00120

    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.

    watch from here

  6. step 21 of 22

    abababcabababcababc00120

    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.

    watch from here

  7. step 22 of 22

    abababcabababcababc00120

    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.

    watch from here

the steps, in plain words
  1. the pattern's first letter alone has no border: 0Python line 9
  2. 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
  3. write how long its border isPython line 19
  4. 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
  5. every letter matched: mark a match, and move the pattern on so its border lines upPython lines 25, 26 and 27
  6. 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
  7. 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 nn 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

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, 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
how long the worst takes, at a billion comparisons a second
nnletters comparedtime
1,0002,497about 2.5 microseconds
100,000249,997about 250 microseconds
10,000,00024,999,997about 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, nn letters and ⌈n2⌉\lceil \frac{n}{2} \rceil, half of nn 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, Θ(n)\Theta(n), and only the fixed multiple tells them apart.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta text of a's and a pattern of b's, half as longworsta text of a's and a pattern of a's ending in b, half as long
letters comparednn2n+⌈n2⌉−32n + \lceil \frac{n}{2} \rceil - 3, from 3 letters on
how the letters compared grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n)\Theta(n)
ceiling, OOO(n)O(n)O(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n)\Omega(n)

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.

textpatterntablesearchin all
abababcabababc5813
abababababab3811
everythingzoo2810
aaaaaaaaaaaaaaab91423
ababaababaa4711
The watch page's five examples, each count split into the table's and the search's. The 10 a's cost the most, as aaaaab's b falls back through every border.
nbestworst
6612
7715
101022
The two cases, a pattern half the text, rounded up. At 10 letters the worst costs 22.
patterncomparisons
b6
ab11
aab12
aaab13
aaaab14
aaaaab15
A text of 6 a's and a pattern of a's ending in b, of each length. The longer the pattern, the more it costs.

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.

Question 1: how many comparisons, FF, on a text of nn a's and a pattern of mm b's, mm half of nn rounded up?
  1. the move: the table for b's

    the line:
    table: m−1comparisons\begin{gathered} \text{table: } m - 1 \\ \text{comparisons} \end{gathered}
    startbbbbbb
    border012
    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 m−1m - 1 such starts. For bbb, 2.

  2. the move: one comparison a place

    the line:
    search: 1 comparisonat each place\begin{gathered} \text{search: 1 comparison} \\ \text{at each place} \end{gathered}

    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.

  3. the move: the places

    the line:
    places: n−m+1\text{places: } n - m + 1

    why it is allowed: From place 1, one place at a time by line 2, to the last. There the pattern's mm letters end under letter nn, so the last place is n−m+1n - m + 1. For 6 letters and 3, places 1 to 4.

  4. the move: add the two

    the line:
    F=nF = n

    why it is allowed: Line 1's m−1m - 1, and 1 at each of line 3's n−m+1n - m + 1 places, by line 2, added; the mm's cancel. For 6, 2 + 4, which is 6.

  5. the move: no search costs less

    the line:
    no text and pattern ofthese lengths cost less\begin{gathered} \text{no text and pattern of} \\ \text{these lengths cost less} \end{gathered}

    why it is allowed: The table compares at least once for each of the m−1m - 1 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 n−m+1n - m + 1. So it has moved on at least n−m+1n - m + 1 times, and the search compared at least that often. m−1m - 1 and n−m+1n - m + 1 added are nn, line 4's FF. 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.

  6. the move: a ceiling

    the line:
    F≤nF \le n

    why it is allowed: By line 4, FF is nn.

  7. the move: read the bound

    the line:
    F∈O(n)F \in O(n)

    why it is allowed: By line 6, with the fixed multiple 1.

  8. the move: a floor

    the line:
    F≥nF \ge n

    why it is allowed: By line 4 again.

  9. the move: read the bound

    the line:
    F∈Ω(n)F \in \Omega(n)

    why it is allowed: By line 8, with the fixed multiple 1.

  10. the move: both together

    the line:
    F∈Θ(n)F \in \Theta(n)

    why it is allowed: Lines 7 and 9 bound FF by the same growth, the text's.

try it with a small nn: at n=6n = 6, line 4 gives F=6F = 6, which you can work out by hand

Question 2: how many comparisons, MM, on a text of nn a's and a pattern of mm letters, a's ending in b, mm half of nn rounded up?
  1. the move: the table's a's

    the line:
    table, the a’s:m−2\begin{gathered} \text{table, the a's:} \\ m - 2 \end{gathered}

    why it is allowed: Each of the m−2m - 2 starts from 2 letters to m−1m - 1 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.

  2. the move: the table's b

    the line:
    table, the b:m−1\begin{gathered} \text{table, the b:} \\ m - 1 \end{gathered}
    startaaaaab
    border010
    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 m−2m - 2. It falls back 1 letter at a time, by line 1, to a border of nothing, and differs at each: borders m−2m - 2 down to 0, m−1m - 1 comparisons. For aab, 2.

  3. the move: the table

    the line:
    table: 2m−3\text{table: } 2m - 3

    why it is allowed: Lines 1 and 2 added. For aab, 3.

  4. the move: the first place

    the line:
    place 1:m comparisons\begin{gathered} \text{place 1:} \\ m \text{ comparisons} \end{gathered}

    why it is allowed: The pattern's m−1m - 1 a's match the text's, then its b differs from an a.

  5. the move: each place after

    the line:
    each place after:2 comparisons\begin{gathered} \text{each place after:} \\ 2 \text{ comparisons} \end{gathered}
    placeletters abovecomparisons
    1aaa3
    2aaa2
    3aaa2
    4aaa2
    search9
    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 m−1m - 1 a's matched end with a border of m−2m - 2 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.

  6. the move: the places

    the line:
    places: n−m+1\text{places: } n - m + 1

    why it is allowed: One place at a time, by line 5. At the last place the pattern's mm letters end under letter nn, so the last place is n−m+1n - m + 1. For 6 letters and 3, places 1 to 4.

  7. the move: the search

    the line:
    search: m+2(n−m)\text{search: } m + 2(n - m)

    why it is allowed: Line 4's mm, then 2 at each place after place 1, by line 5. Line 6's places less place 1 are n−mn - m. For 6, 3 + 2 times 3.

  8. the move: multiply out

    the line:
    search: 2n−m\text{search: } 2n - m

    why it is allowed: Twice all of n−mn - m is twice nn less twice mm. Adding line 7's mm gives one mm back: 2n−m2n - m. For 6, 12 - 3, which is 9.

  9. the move: add the two

    the line:
    in all: 2n+m−3\text{in all: } 2n + m - 3

    why it is allowed: Lines 3 and 8 added: 2m−32m - 3 and 2n−m2n - m. For 6, 3 + 9, which is 12.

  10. the move: the pattern half the text

    the line:
    M=2n+⌈n2⌉−3M = 2n + \lceil \frac{n}{2} \rceil - 3

    why it is allowed: Line 9 with mm as half of nn rounded up. For 6, 12 + 3 - 3, which is 12; for 7, 14 + 4 - 3, which is 15.

  11. the move: a ceiling

    the line:
    M≤3nM \le 3n

    why it is allowed: Half of nn rounded up is at most nn, so line 10 is at most 3n−33n - 3, less than 3n3n. For 6, 12 against 18.

  12. the move: read the bound

    the line:
    M∈O(n)M \in O(n)

    why it is allowed: By line 11, with the fixed multiple 3.

  13. the move: a floor

    the line:
    M≥nM \ge n

    why it is allowed: From 3 up, half of nn rounded up is at least 2. So line 10 is at least 1 less than twice nn, and that is at least nn. For 6, 12 against 6.

  14. the move: read the bound

    the line:
    M∈Ω(n)M \in \Omega(n)

    why it is allowed: By line 13, with the fixed multiple 1.

  15. the move: both together

    the line:
    M∈Θ(n)M \in \Theta(n)

    why it is allowed: Lines 12 and 14 bound MM by the same growth, the text's.

try it with a small nn: at n=6n = 6, line 10 gives M=12M = 12, which you can work out by hand

Question 3: PP is the most any text of nn letters and pattern of ⌈n2⌉\lceil \frac{n}{2} \rceil letters can cost. Why is it question 2's MM, and which pattern length costs the most?
  1. the move: what a table comparison does

    the line:
    table: a comparisonsettles a start’s border,or shortens the border so far\begin{gathered} \text{table: a comparison} \\ \text{settles a start's border,} \\ \text{or shortens the border so far} \end{gathered}

    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, m−1m - 1. One that differs with a border left falls back to a shorter border.

  2. the move: a ceiling for the table

    the line:
    table: at most 2m−3\text{table: at most } 2m - 3
    startaaaaaaaab
    border after120
    comparisons113
    settling111
    shortenings002
    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 m−2m - 2 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 m−2m - 2 shortenings. Line 1's m−1m - 1 settling comparisons plus these, 2m−32m - 3. For aaab, 3 + 2, which is 5.

  3. the move: what a search comparison does

    the line:
    search: a comparison moves onthe text letter or the place\begin{gathered} \text{search: a comparison moves on} \\ \text{the text letter or the place} \end{gathered}

    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.

  4. the move: a ceiling for the search

    the line:
    search: at most(n−1)+(n−m)+1,which is 2n−m\begin{gathered} \text{search: at most} \\ (n - 1) + (n - m) + 1, \\ \text{which is } 2n - m \end{gathered}
    comparisontext letter's positionplace
    111
    221
    331
    432
    542
    643
    753
    854
    964
    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 nn, at most n−1n - 1 moves. The place goes from 1 to at most n−m+1n - m + 1, at most n−mn - m. 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, 2n−m2n - m. For 6 letters and 3, 5 + 3 + 1, which is 9.

  5. the move: no search costs more

    the line:
    at most 2n+m−3\text{at most } 2n + m - 3
    mtable at mostsearch at mostin all
    211011
    33912
    45813
    57714
    69615
    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 nn letters and pattern of mm letters, mm at least 2. Question 2's lines 1 to 9 hold for any mm; only line 10 makes it half of nn. So a's ending in b against a's count exactly this many at every mm: none costs more. For 6 letters and 3, 12.

  6. the move: the most at half the text

    the line:
    P=2n+⌈n2⌉−3P = 2n + \lceil \frac{n}{2} \rceil - 3

    why it is allowed: Line 5 with mm as half of nn rounded up, question 2's MM. For 6, 12.

  7. the move: the dearest length

    the line:
    the dearest length:the whole text, 3n−3\begin{gathered} \text{the dearest length:} \\ \text{the whole text, } 3n - 3 \end{gathered}

    why it is allowed: Line 5 grows with mm, so among patterns of 2 letters or more the dearest is as long as the text, with mm as nn. Question 2's line 9 with mm as nn counts exactly that, 15 for 6 letters. A pattern of 1 letter has no table and compares each text letter once, nn, which is less.

try it with a small nn: at n=6n = 6, line 6 gives P=12P = 12, 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.

aaaaaa, aab, every step written down
stepthe rowwhat happensletters compared
1Look 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
20The first letter, a, alone has no border: write 0.00
30a matches the letter after a border of nothing, so the first 2 letters have a border one longer: 1.01
40, 1Write it: the first 2 letters have a border 1 letter long.0, 11
50, 1b 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, 12
60, 1b is not a, the first letter, and there is no shorter border left to fall back to.0, 13
70, 1, 0Write it: the first 3 letters have a border of nothing.0, 1, 03
80, 1, 0The text's a at position 1 matches the pattern's a.0, 1, 04
90, 1, 0The text's a at position 2 matches the pattern's a.0, 1, 05
100, 1, 0The text's a at position 3 is not the pattern's b.0, 1, 06
110, 1, 02 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, 06
120, 1, 0The text's a at position 3 matches the pattern's a.0, 1, 07
130, 1, 0The text's a at position 4 is not the pattern's b.0, 1, 08
140, 1, 02 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, 08
150, 1, 0The text's a at position 4 matches the pattern's a.0, 1, 09
160, 1, 0The text's a at position 5 is not the pattern's b.0, 1, 010
170, 1, 02 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, 010
180, 1, 0The text's a at position 5 matches the pattern's a.0, 1, 011
190, 1, 0The text's a at position 6 is not the pattern's b.0, 1, 012
200, 1, 0The pattern no longer fits in the rest of the text. It stands nowhere in the text. That took 12 comparisons.0, 1, 012

In all, 12 letters compared. The formula from section 4, 2n+⌈n2⌉−32n + \lceil \frac{n}{2} \rceil - 3, gives M=12M = 12 at n=6n = 6: 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 nn. 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 nn times. So at most 2n2n, 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.

methodcomparisonsalso
brute force10
Horspool6
Knuth-Morris-Pratt14its table's 4 included
Rabin-Karp67 fingerprints
toothpaste and paste, each method's own count. No start of paste has a border, so the table costs 4 and finds none.
methodcomparisonsalso
brute force30
Horspool6
Knuth-Morris-Pratt22its table's 7 included
Rabin-Karp07 fingerprints
10 a's and aaaab. Brute force compares all 5 letters at each of 6 places; Knuth-Morris-Pratt 5 at place 1, then 2 at each place after. Rabin-Karp's fingerprints never agree, so it compares no letter.

race them on one row of your own