String matching

O(n)·O(m + 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.

mmiissssiissssiippppii··rriivveerr··rruunnss··ppaasstt··tthhee··mmiissssiissssiippppii··ddeellttaammiissssiissiippppii????????????????????all: ??TextPatternLast seen atGood suffix
  • Where the pattern sits

The text is 49 characters and the pattern is 10; nothing has been compared yet.

The text is 49 characters and the pattern is 10; nothing has been compared yet.
  1. 1build the bad-character table: the last place each character appears in the pattern
  2. 2build the good-suffix table: where else a matched ending could line up
  3. 3line the pattern up and compare from its right-hand end
  4. 4the characters agree, so step left
  5. 5they differ, so ask both rules how far it is safe to move
  6. 6every character agreed: record an occurrence here
  7. 7move by whichever rule says the larger number
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(m + alphabet)
n at n=49 predicts 49; this run took 0.

Boyer-Moore

Boyer-Moore compares from the right-hand end like Horspool, but keeps two tables. The bad-character rule asks where the mismatching text character last appears in the pattern. The good-suffix rule asks where else in the pattern the part that already matched could line up. Both give a safe distance, and the algorithm moves by the larger.

How far it jumps

Ask two rules how far is safe, and take the larger answer.

When it is the right choice

It is the classical answer for searching a long text with a long pattern, and the one the good implementations are descended from. The extra table costs O(m) to build and its arithmetic is fiddly, which is exactly why Horspool — bad-character only — is more common in practice. Where it pays is text that partially matches often: the good-suffix rule uses what matched, which the bad-character rule throws away.

How it works

Worth noticing

Cost

Best
O(n / m)
Average
O(n)
Worst
O(n · m)
Extra space
O(m + 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