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··ccaatt··ssaatt··oonn··tthheeiirr··mmaatt;;··hhaallff··tthhee··ddaayy··wwaass··eeaarrllyyccaattP hash: ?P hash?T hash: ?T hash?base: 256base256mod: 101mod101TextPatternRolling hash
  • Where the pattern sits

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

The text is 48 characters and the pattern is 3; nothing has been compared yet.
  1. 1work out the pattern's hash, one character at a time
  2. 2work out the hash of the first window of the text
  3. 3compare the two hashes
  4. 4the hashes differ, so this window cannot possibly match
  5. 5the hashes agree, so check the characters: this is only a candidate
  6. 6the characters agree too, so record a real occurrence
  7. 7the characters differ: a collision, not a match
  8. 8roll the hash: drop the leading character and add the new trailing one
Character comparisons
0
Hashes computed
0
Collisions
0
Hash set-up steps
0
Alignments skipped
0
Occurrences found
0

Complexity

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

Rabin-Karp

Rabin-Karp hashes the pattern once, then hashes each window of the text in turn — each one obtained from the last by dropping the leading character and adding the trailing one, which costs a fixed amount of arithmetic rather than a pass over the window. When a window’s hash equals the pattern’s, the characters are compared to see whether it is a real match or a collision.

How far it jumps

Do not jump at all — compare a number, and verify every hit.

When it is the right choice

Its real home is searching for many patterns at once, since one pass over the text can be checked against a whole set of hashes, and plagiarism detection and file-difference tools use it for exactly that. For one pattern it rarely beats Boyer-Moore, because it looks at every character of the text and skips nothing. The reason it is here is the verification step, which is the honest part almost every description leaves out.

How it works

Worth noticing

Cost

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