Skip to content
StackDecode
StringsAnimated

Boyer–Moore String Search

Compare from the pattern end and skip ahead using mismatch rules.

Time

O(n/m) best, O(n · m) worst

Extra space

O(σ)

Use it for

Long patterns in long texts; text editors.

How it works

  1. Build a "bad character" table: the last position of each character in the pattern.
  2. Align the pattern and compare from its RIGHT end towards the left.
  3. On a mismatch with text character c, shift the pattern so its last occurrence of c lines up with c in the text (or past it if c is not in the pattern at all).
  4. Often skips many characters at once, so it can be sub-linear in practice.

Watch it run

Loading animation…