String matching

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

aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabb????????????????????????????????????????????????TextPatternz, patternz, text
  • Where the pattern sits

The text is 20 characters and the pattern is 4; nothing has been compared yet.

The text is 20 characters and the pattern is 4; nothing has been compared yet.
  1. 1join the pattern, a separator and the text into one string
  2. 2walk along it, working out how much of the start repeats at each position
  3. 3inside the window, copy the answer already known for the matching position near the start
  4. 4compare character by character from wherever the copy left off
  5. 5record the length, and move the window if this match reaches further right
  6. 6a length equal to the pattern means the pattern occurs here
Character comparisons
0
Answers copied from the window
0
Alignments skipped
0
Occurrences found
0

Complexity

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

The Z-algorithm

The Z-algorithm joins the pattern, a separator that appears in neither string, and the text into one string, and computes for every position how many characters from there match the very beginning. Any position whose value equals the pattern length is an occurrence. It keeps a window — the match starting furthest left that reaches furthest right — and inside that window copies an answer it already has instead of comparing again.

How far it jumps

Reuse the answer already known for the window you are inside.

When it is the right choice

It is the same linear guarantee Knuth-Morris-Pratt gives, from a different and arguably more transparent idea, and the z-array itself is useful well beyond matching: longest common prefixes, periodicity, and the borders that Knuth-Morris-Pratt’s own table records. The cost is the space — the array is as long as the text plus the pattern, where a prefix table is only as long as the pattern.

How it works

Worth noticing

Cost

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