String matching

O(n)·O(alphabet) space
Whole text

Drag to pan; pinch or Ctrl+scroll to zoom, which stops at the whole text; arrow keys pan once the picture has focus.

tthhee··qquuiicckk··bbrroowwnn··ffooxx··jjuummppss··oovveerr··tthhee··llaazzyy··ddooggtthheerest: 3rest3TextPatternShift table
  • Where the pattern sits

The text is 43 characters and the pattern is 3; nothing has been compared yet.

The text is 43 characters and the pattern is 3; nothing has been compared yet.
  1. 1build the shift table: how far each character sits from the end of the pattern
  2. 2line the pattern up and compare from its right-hand end
  3. 3the characters agree, so step left
  4. 4they differ, so this position fails
  5. 5every character agreed: record an occurrence here
  6. 6look up the text character under the pattern end, and shift by what the table says
Character comparisons
0
Table-building steps
0
Alignments tried
0
Alignments skipped
0
Occurrences found
0

Complexity

BestO(n / m)
AverageO(n)
WorstO(n · m)
Extra spaceO(alphabet)
n at n=43 predicts 43; this run took 0.

Boyer-Moore-Horspool

Horspool lines the pattern up, compares from its right-hand end leftwards, and on any mismatch looks at the text character sitting under the pattern’s last position. The shift table says how far that character is from the end of the pattern, and the pattern jumps by exactly that much — which can be the whole pattern length when the character does not appear in the pattern at all.

How far it jumps

Move so the offending character lands where it belongs.

When it is the right choice

This is the one to reach for on ordinary text with a reasonably long pattern and a large alphabet: most characters in English do not appear in a ten-character pattern, so most shifts are the full pattern length and most of the text is never looked at. It degrades to naive search’s worst case on a small alphabet or a repetitive text, and it is a simplification of full Boyer-Moore — one table instead of two — which is why the next page exists.

How it works

Worth noticing

Cost

Best
O(n / m)
Average
O(n)
Worst
O(n · m)
Extra space
O(alphabet)
Longest text
160 characters
Longest pattern
24 characters

The limits are pedagogical rather than technical: one column is drawn per character, and a run has to stay short enough to sit and watch. A text and pattern that would take more than three thousand steps on this algorithm are refused before a single step is generated — and because that depends on the text itself and not only on its length, the tool counts the steps first rather than guessing from a formula.

Worth comparing

All matching algorithms