Skip to content
StackDecode
StringsAnimated

Naive Pattern Matching

Slide the pattern along the text and compare at every position.

Time

O(n · m)

Extra space

O(1)

Use it for

Short texts; the baseline.

How it works

  1. Line the pattern up with the start of the text.
  2. Compare characters left to right. If every character matches, record the position.
  3. On the first mismatch, slide the pattern one place to the right and start comparing again.
  4. Simple, but in the worst case it re-compares the same text characters many times: O(n·m).

Watch it run

Loading animation…