Boyer-Moore-Horspool
how it works
The idea on the watch page's first example, paste in toothpaste. Then the whole method on it, step by step. A position is a letter's number in the text, from 1; in the watch page's table, * means any other letter.
Look for paste in toothpaste. First write a table from the pattern alone. For each letter but its last, how far it stands from the end: p 4, a 3, s 2, t 1. Any other letter jumps 5, the whole pattern. A letter found twice before the last keeps the copy nearer the end, the smaller jump: in bbb, b jumps 1, not 2. Put paste under the text's start and compare from its last letter back. The text's h is not e: 1 comparison. Look up h, the text's letter above the pattern's last. The jump slides the pattern right until its nearest copy of that letter lies under the text's letter; a smaller slide puts a different letter there, which cannot match. h is not in the table, so the pattern jumps 5, past h. At place 6, e, t, s, a and p all match, so paste stands at place 6: 5 comparisons. e stands only last in paste, so it is not in the table: it jumps 5, past the end. 2 places cost 1 + 5, which is 6 comparisons; brute force tries all 6 places and makes 10. The code below counts places from 0 and returns them in a list, so it returns [5].
| letter | p | a | s | t | any other |
|---|---|---|---|---|---|
| jump | 4 | 3 | 2 | 1 | 5 |
| 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|
| i | n | t | e | n | t |
| t | e | n | |||
| t | e | n |
| place | letters above | compared from the end | comparisons | jump |
|---|---|---|---|---|
| 1 | tooth | h is not e | 1 | h: 5 |
| 6 | paste | all 5 match | 5, a match | e: 5 |
| all | 6 |
step 1 of 17
Look for paste in toothpaste. First write a table, from the pattern alone, of how far it may jump.
what it remembers to know where it is
- pattern stands at place
- 1
- text letter under its last letter
- not yet
- jump allowed
- not yet
Where it says not yet, nothing is held there at that moment.
step 6 of 17
Any other letter is nowhere in the pattern before its last letter, so with it under the pattern's last letter the pattern may jump its whole length, 5.
what it remembers to know where it is
- pattern stands at place
- 1
- text letter under its last letter
- not yet
- jump allowed
- not yet
Where it says not yet, nothing is held there at that moment.
step 7 of 17
The text's h at position 5 is not the pattern's e, so the pattern does not stand here.
what it remembers to know where it is
- pattern stands at place
- 1
- text letter under its last letter
- not yet
- jump allowed
- not yet
Where it says not yet, nothing is held there at that moment.
step 9 of 17
Jump the pattern on 5 places, to place 6, and compare from its last letter again.
what it remembers to know where it is
- pattern stands at place
- 6
- text letter under its last letter
- h
- jump allowed
- 5
step 15 of 17
Every letter matched: the pattern stands at place 6. Mark it.
what it remembers to know where it is
- pattern stands at place
- 6
- text letter under its last letter
- h
- jump allowed
- 5
step 17 of 17
The pattern would run past the end of the text. It stands at 1 place. That took 6 comparisons.
what it remembers to know where it is
- pattern stands at place
- 6
- text letter under its last letter
- e
- jump allowed
- 5
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- for each letter of the pattern but its last, write how far it stands from the end; any other letter, the whole lengthPython lines 8, 9 and 10
- while the pattern fits under the text, compare it with the text from its last letter back, until one differsPython lines 13, 14, 16 and 17
- if every letter matched, mark a matchPython lines 18 and 19
- look up the text letter under the pattern's last letter, and jump the pattern on that farPython line 21
- the pattern would run past the end of the text, so every match is foundPython line 22
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 boyer_moore_horspool(text, pattern):
"""Find every place a pattern stands in a text, jumping ahead by a table.
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)
jump = {} # each letter's jump, kept by its number, ord(letter)
for i in range(m - 1): # each letter of the pattern but its last
jump[ord(pattern[i])] = m - 1 - i # how far it stands from the end
places = []
place = 0
while place + m <= n: # while the pattern fits under the text
j = m - 1
# compare from the pattern's last letter back, until one differs
while j >= 0 and text[place + j] == pattern[j]:
j -= 1
if j < 0: # every letter matched
places.append(place) # so it stands here
# jump by the text's letter above the pattern's last; any other, m
place += jump.get(ord(text[place + m - 1]), m)
return places # the pattern would run past the end: every match found
how it scales
The plot counts the comparisons on a text of letters and a pattern half as long, rounded up, in two ways. The best shares no letter with the text and jumps the whole pattern. The worst matches at every place and jumps 1. Measured from 10 to 10,000.
Each mark across or up is ten times the one before. The best line lies flat: 2 comparisons at every size measured, as each is even; an odd size costs 1. The worst climbs two marks up for each mark across: 2,550 at 100, 250,500 at 1,000. Ten times the letters, about 100 times the comparisons. 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, half as longsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 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 | 250,500 | about 251 microseconds |
| 100,000 | 2,500,050,000 | about 2.5 seconds |
| 10,000,000 | 25,000,005,000,000 | about 6.9 hours |
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 Boyer-Moore-Horspool'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 last letter differs at once and a jumps the whole pattern,
the fewest; and all a, so every letter matches at every place and a jumps
1, the most. It prints the comparisons for each, by count
below, which counts 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 boyer_moore_horspool(text, pattern):
"""Find every place a pattern stands in a text, jumping ahead by a table.
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)
jump = {} # each letter's jump, kept by its number, ord(letter)
for i in range(m - 1): # each letter of the pattern but its last
jump[ord(pattern[i])] = m - 1 - i # how far it stands from the end
places = []
place = 0
while place + m <= n: # while the pattern fits under the text
j = m - 1
# compare from the pattern's last letter back, until one differs
while j >= 0 and text[place + j] == pattern[j]:
j -= 1
if j < 0: # every letter matched
places.append(place) # so it stands here
# jump by the text's letter above the pattern's last; any other, m
place += jump.get(ord(text[place + m - 1]), m)
return places # the pattern would run past the end: every match found
def count(text, pattern):
"""How many comparisons boyer_moore_horspool makes: one for each letter
of the text it compares with a letter of the pattern."""
n, m = len(text), len(pattern)
jump = {}
for i in range(m - 1):
jump[ord(pattern[i])] = m - 1 - i
compared = 0
place = 0
while place + m <= n:
j = m - 1
while j >= 0:
compared += 1
if text[place + j] != pattern[j]:
break
j -= 1
place += jump.get(ord(text[place + m - 1]), m)
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 a's, rounded up."""
return "a" * n, "a" * ((n + 1) // 2)
if __name__ == "__main__":
print(f"{'n':>7} {'all b':>8} {'all a':>12}")
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)):>12}")
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. The letters set the jumps: the best jumps the whole pattern, the worst 1. For 6 letters and 3, the best makes 2 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. At 10,000 letters the worst is 5,000 times 5,001: 5,000 times 5,000, which is 25,000,000, plus 5,000. They are the pieces and half of , and the first is nearly all of it. So how a cost grows is what tells one method from another, and the bounds keep just that.
| 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, half as long | |
|---|---|---|
| letters compared | ||
| how the letters compared grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: a jump for each different letter before the pattern's last, 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 | places tried | comparisons |
|---|---|---|---|
| toothpaste | paste | 2 | 6 |
| banana | ana | 3 | 7 |
| everything | zoo | 3 | 3 |
| aaaaaaaaaa | baaaa | 6 | 30 |
| n | best | worst |
|---|---|---|
| 6 | 2 | 12 |
| 7 | 1 | 16 |
| 10 | 2 | 30 |
| pattern | places tried | comparisons |
|---|---|---|
| a | 6 | 6 |
| aa | 5 | 10 |
| aaa | 4 | 12 |
| aaaa | 3 | 12 |
| aaaaa | 2 | 10 |
| aaaaaa | 1 | 6 |
where the formula comes from
Questions 1 and 2 count the comparisons, the plot's two lines. Question 3 keeps the pattern at 5 letters as the text grows, so every jump moves it 5 places.
the move: the jump for a
the line:letter b any other jump 1 3 The table for bbb. Of the two b's before the last, the nearer stands 1 from the end; any other letter jumps the whole pattern, 3. why it is allowed: The pattern is all b. At every place the text's letter above the pattern's last is an a. a is not in the table, so the pattern jumps its whole length, .
the move: one comparison a place
the line:why it is allowed: The pattern's last letter, b, is compared first, with an a, and differs. So each place tried costs 1.
guess it, thenthe move: the last place
the line:1 2 3 4 5 6 a a a a a a b b b Positions 1 to 6, the text above and the pattern at its last place below. Its 3 letters end under letter 6, so they start under 6 - 3 + 1, which is 4. why it is allowed: At its last place, the pattern's last letter is under the text's last, , and its letters cover letters to . For 6 letters and 3, place 4.
guess it, thenthe move: the second place
the line:n m last place second place places tried 6 3 4 4 1 and 4 7 4 4 5 1 8 4 5 5 1 and 5 A text of a's, a pattern of b's half as long. Place 1 + m is tried exactly when it is at most the last place. why it is allowed: By line 1, a jump of from place 1 lands on place , which must not pass line 3's last place. For 6 letters and 3, place 4 is tried; for 7 and 4, place 5 passes place 4.
guess it, thenthe move: the pattern half the text
the line:why it is allowed: The cases take a pattern half the text, rounded up, as its . Half of rounded up and half of rounded down add up to , so is the half rounded down. For 6, 3 and 3; for 7, 4 and 3.
guess it, thenthe move: take 1 from both sides
the line:why it is allowed: Line 4, with 1 taken from both sides. For 6 letters and 3, 3 is at most 3.
guess it, thenthe move: put in line 5
the line:why it is allowed: Line 6, with line 5's halves put in for and . For 7, 4 is more than 3.
guess it, thenthe move: the halves equal
the line:why it is allowed: Rounding up never gives less than rounding down, so at most means equal, which happens only when is whole. For 6, 3 and 3.
guess it, thenthe move: no third place
the line:why it is allowed: Two jumps of , by line 1. By line 5, is at least , so place starts past letter .
guess it, thenthe move: one place or two
the line:n half down half up places F 6 3 3 2 2 7 3 4 1 1 For 6, 3 - 3 + 2 is 2; for 7, 3 - 4 + 2 is 1. why it is allowed: By lines 8 and 9, 2 places for an even , where is 0, and 1 for an odd one, where it is -1. 1 comparison each by line 2. For 6, 2; for 7, 1.
guess it, thenthe move: no search costs less
the line:why it is allowed: Every search compares at place 1, at least 1. No jump is more than , the whole pattern. So for an even the first jump lands at most on place , the last by lines 3 and 5. So a second place is always tried, at least 2. For 6, 2.
guess it, thenthe move: a ceiling
the line:why it is allowed: Half of rounded down is never more than half rounded up, so line 10 is at most 0 + 2. For 6, 2.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 12, with the fixed multiple 2: at most 2 times 1, however long the text.
guess it, thenthe move: a floor
the line:why it is allowed: Half of rounded up is at most 1 more than half rounded down, so line 10 is at least -1 + 2. For 7, 1.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 14, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 13 and 15, a ceiling and a floor of the same growth: a fixed number, however long the text.
guess it, then
try it with a small : at , line 10 gives , which you can work out by hand
the move: a place's most
the line:why it is allowed: At a place the pattern's letters are compared from its last back, one each, until one differs. It has letters, so at most .
the move: every letter matches
the line:place text pattern comparisons 1 aaa aaa 3, a match 2 aaa aaa 3, a match 3 aaa aaa 3, a match 4 aaa aaa 3, a match all 12 A text of 6 a's and the pattern aaa. At each of the 4 places all 3 letters match. 4 times 3 is 12. why it is allowed: The text and the pattern are all a, so every letter matches from the end back: line 1's most, , at every place tried, each a match.
guess it, thenthe move: a jumps 1
the line:letter a any other jump 1 3 The table for aaa. The nearest a before the last stands 1 from the end; any other letter jumps 3. why it is allowed: The text's letter above the pattern's last is always a. The nearest a before the last stands 1 from the end, so the letter a jumps 1. For of 1 or 2 the pattern is one a, with no letter before its last, so it jumps its whole length, 1 again. The pattern moves on one place at a time.
guess it, thenthe move: the places
the line:why it is allowed: By line 3, every place from 1 to the last, where the pattern's letters lie under letters to . For 6 letters and 3, places 1 to 4.
guess it, thenthe move: the pattern half the text
the line:why it is allowed: The case takes as half of rounded up. Half of rounded up and half rounded down add up to , so is half rounded down, and is 1 more. For 6, 3 and 4.
guess it, thenthe move: multiply by the places
the line:why it is allowed: Line 2's at each place, times line 4's places, both written in by line 5. For 6, 3 times 4, which is 12; for 7, 4 times 4, which is 16.
guess it, thenthe move: no search costs more
the line:why it is allowed: By line 1 no place costs more than , and every jump is at least 1. So no search tries more than line 4's places: at most line 6's . For 6, 12.
guess it, thenthe move: a ceiling
the line:why it is allowed: For of 1 or more: is at most , and is whole, so is at most . is a whole number below , so is at most . Multiply the two. For 6, 12 is at most 36.
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: a floor
the line:why it is allowed: Rounding up never makes a number smaller, so is at least . Rounding down takes off less than 1, so is more than . Multiply the two, as times is . For 6, 12 against 9.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 10, with the fixed multiple a quarter.
guess it, thenthe move: both together
the line:why it is allowed: Lines 9 and 11 bound by the same growth.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
the move: one comparison, a jump of 5
the line:why it is allowed: Question 1's lines 1 and 2 with as 5: a, not in the pattern, jumps the whole pattern, 5. The pattern's last b differs from an a at once.
the move: the places tried
the line:n places tried comparisons 5 1 1 9 1 1 10 1 and 6 2 14 1 and 6 2 15 1, 6 and 11 3 A text of a's and the pattern bbbbb. A place is added each time the text reaches a whole 5 more letters. why it is allowed: Each jump adds 5, by line 1. No place past fits, question 1's line 3 with as 5. For 14 letters, places 1 and 6; place 11 passes place 10.
guess it, thenthe move: a place for each 5 letters
the line:why it is allowed: By line 2, a place fits when it is at most , so place 1 needs 5 letters, place 6 needs 10, and each place after 5 more. So the places are rounded down, 1 comparison each by line 1. For 14, 2.
guess it, thenthe move: a ceiling
the line:why it is allowed: Rounding down never makes a number bigger. For 14, 2 against 2.8.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple a fifth.
guess it, thenthe move: a floor
the line:n n / 5 J n / 10 5 1 1 0.5 9 1.8 1 0.9 14 2.8 2 1.4 19 3.8 3 1.9 A text of a's and the pattern bbbbb. J never falls below a tenth of n. why it is allowed: By line 3. From of 5 up, is at least 1. Below 2, it rounds down to 1, more than half of it. From 2 up, rounding down takes off less than 1, at most half of it. Either way keeps at least half, . For 9, 1 against 0.9.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple a tenth.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth. At 10,000 letters, 2,000 comparisons, a fifth of a comparison a letter.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
count it yourself
A text of 6 a's and the pattern aaa, question 2's worst at 6. At each place all 3 letters match from the end, and a jumps 1. A position is a letter's number in the text, from 1.
| step | the row | what happens | letters compared |
|---|---|---|---|
| 1 | Look for aaa in aaaaaa. First write a table, from the pattern alone, of how far it may jump. | 0 | |
| 2 | 1 | The nearest a before the pattern's last letter stands 1 letter from its end. With a in the text under the pattern's last letter, the pattern may jump 1.1 | 0 |
| 3 | 1, 3 | Any other letter is nowhere in the pattern before its last letter, so with it under the pattern's last letter the pattern may jump its whole length, 3.1, 3 | 0 |
| 4 | 1, 3 | The text's a at position 3 matches the pattern's a.1, 3 | 1 |
| 5 | 1, 3 | The text's a at position 2 matches the pattern's a.1, 3 | 2 |
| 6 | 1, 3 | The text's a at position 1 matches the pattern's a.1, 3 | 3 |
| 7 | 1, 3 | Every letter matched: the pattern stands at place 1. Mark it.1, 3 | 3 |
| 8 | 1, 3 | a is under the pattern's last letter, so the table allows a jump of 1.1, 3 | 3 |
| 9 | 1, 3 | Jump the pattern on 1 place, to place 2, and compare from its last letter again.1, 3 | 3 |
| 10 | 1, 3 | The text's a at position 4 matches the pattern's a.1, 3 | 4 |
| 11 | 1, 3 | The text's a at position 3 matches the pattern's a.1, 3 | 5 |
| 12 | 1, 3 | The text's a at position 2 matches the pattern's a.1, 3 | 6 |
| 13 | 1, 3 | Every letter matched: the pattern stands at place 2. Mark it.1, 3 | 6 |
| 14 | 1, 3 | a is under the pattern's last letter, so the table allows a jump of 1.1, 3 | 6 |
| 15 | 1, 3 | Jump the pattern on 1 place, to place 3, and compare from its last letter again.1, 3 | 6 |
| 16 | 1, 3 | The text's a at position 5 matches the pattern's a.1, 3 | 7 |
| 17 | 1, 3 | The text's a at position 4 matches the pattern's a.1, 3 | 8 |
| 18 | 1, 3 | The text's a at position 3 matches the pattern's a.1, 3 | 9 |
| 19 | 1, 3 | Every letter matched: the pattern stands at place 3. Mark it.1, 3 | 9 |
| 20 | 1, 3 | a is under the pattern's last letter, so the table allows a jump of 1.1, 3 | 9 |
| 21 | 1, 3 | Jump the pattern on 1 place, to place 4, and compare from its last letter again.1, 3 | 9 |
| 22 | 1, 3 | The text's a at position 6 matches the pattern's a.1, 3 | 10 |
| 23 | 1, 3 | The text's a at position 5 matches the pattern's a.1, 3 | 11 |
| 24 | 1, 3 | The text's a at position 4 matches the pattern's a.1, 3 | 12 |
| 25 | 1, 3 | Every letter matched: the pattern stands at place 4. Mark it.1, 3 | 12 |
| 26 | 1, 3 | a is under the pattern's last letter, so the table allows a jump of 1.1, 3 | 12 |
| 27 | 1, 3 | The pattern would run past the end of the text. It stands at 4 places. That took 12 comparisons.1, 3 | 12 |
In all, 12 letters compared. The formula from section 4, , gives at : the same.
where you meet it
Horspool cut a famous search down to one table in 1980. Python's own search skips ahead the same way when the text and the pattern are long enough.
Horspool's paper
Boyer and Moore's 1977 search keeps two tables for jumping ahead. Horspool's 1980 paper keeps only the one this page builds, for the text's letter above the pattern's last, and finds it about as fast on ordinary text.
source: R. N. Horspool, Software: Practice and Experience 10(6), 1980, pages 501 to 506, Practical fast searching in strings (opens in a new tab)
Python's find
CPython, the usual Python, searches text, a str, with its fastsearch code, which joins ideas from Boyer-Moore and from Horspool. When the text and the pattern are both long enough, it jumps by a table for the text's letter above the pattern's last, much as this page does. That jump is one part of a longer method.
source: CPython's fastsearch, Objects/stringlib/fastsearch.h (opens in a new tab)
The books' advice
The books name Boyer-Moore, Horspool's starting point, for a long pattern over many different letters. A letter nowhere in the pattern skips the whole pattern, and on English text it reads only a fraction of the letters.
source: the books' volume four, chapter 41
what is used instead
On a repetitive text and pattern, Knuth-Morris-Pratt can cost far less: 10 against 30 on the 10 a's and baaaa, its table included. Brute force needs no table, and can win when the pattern's first letter differs at once but its end matches: 6 against 30 there.
how it compares
The four searches on the watch page's first example, and on 10 a's and baaaa, which cost Horspool as much as its worst at 10. Its table pays on ordinary words and costs on a repeated letter.
| method | comparisons | also |
|---|---|---|
| brute force | 10 | |
| Horspool | 6 | |
| Knuth-Morris-Pratt | 14 | its table included |
| Rabin-Karp | 6 | 7 fingerprints |
| method | comparisons | also |
|---|---|---|
| brute force | 6 | |
| Horspool | 30 | |
| Knuth-Morris-Pratt | 10 | its table included |
| Rabin-Karp | 0 | 7 fingerprints |