String matching

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

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab????????TextPatternPrefix table
  • Where the pattern sits

The text is 60 characters and the pattern is 8; nothing has been compared yet.

The text is 60 characters and the pattern is 8; nothing has been compared yet.
  1. 1build the table by matching the pattern against itself
  2. 2the characters agree, so the repeated prefix grows by one
  3. 3they differ, so fall back to a shorter repeated prefix
  4. 4record how much of the pattern start is repeated up to here
  5. 5now search the text, comparing left to right
  6. 6a mismatch: slide the pattern by what the table says, and leave the text pointer alone
  7. 7the whole pattern agreed: record it, then slide forward by the table
Character comparisons
0
Table-building steps
0
Alignments tried
0
Alignments skipped
0
Occurrences found
0

Complexity

BestO(n + m)
AverageO(n + m)
WorstO(n + m)
Extra spaceO(m)
n + m at n=60 predicts 68; this run took 0.

Knuth-Morris-Pratt

Knuth-Morris-Pratt builds a table over the pattern alone: for each position, the length of the longest proper prefix of the pattern that is also a suffix of the part up to that position. When a mismatch happens after j characters have agreed, that table says how much of those j characters is still usable, so the pattern slides forward by exactly the unusable part and the text pointer never moves back.

How far it jumps

Move by whatever the part that already matched tells you.

When it is the right choice

It is the right choice whenever the worst case matters — the running time is linear in the text length whatever the text is, which none of the naive or Boyer-Moore family can promise. It is also the natural choice when the text arrives as a stream, because the text pointer never goes backwards and so nothing has to be kept. What it is not is the fastest in practice on ordinary text: Boyer-Moore's skips are bigger when the alphabet is large, and Knuth-Morris-Pratt still touches every character at least once.

How it works

Worth noticing

Cost

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