String matching

O(n + m)·O(1) 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··ddooggtthheealways: 1always1TextPatternShift by
  • 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. 1line the pattern up at the next position in the text
  2. 2compare the pattern against the text, left to right
  3. 3they differ, so give up on this position
  4. 4every character agreed: record an occurrence here
  5. 5move along by exactly one character and start again
Character comparisons
0
Alignments tried
0
Alignments skipped
0
Occurrences found
0

Complexity

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

Naive search

Naive search lines the pattern up at position 0, compares characters left to right until one disagrees or the pattern runs out, and then moves the pattern along by one and starts again. It keeps no table and remembers nothing between attempts, which is both its whole simplicity and its whole cost.

How far it jumps

Move one. Always.

When it is the right choice

For a short pattern in a short text it is genuinely the right choice: it has no precomputation to pay for, it uses no extra memory, and its inner loop is about as cheap as a loop gets. It is also what almost every standard library does for small inputs. What it cannot survive is a text and a pattern that agree for a long way and then disagree — try the repeated-characters scenario and watch the comparison counter against any other page here.

How it works

Worth noticing

Cost

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