Algorithms · Visualized
String: Boyer-Moore
String Matching
Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.
Boyer-Moore searches for a pattern by comparing it against the text from RIGHT to LEFT, and on a mismatch uses a precomputed bad-character table — the rightmost position of each pattern character — to shift the pattern forward by several positions in one jump. Time: O(n/m) with big alphabets average, O(n·m) worst; space: O(m + alphabet size) for the precomputed tables.
Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.
Boyer-Moore String Search
String MatchingBoyer-Moore searches for a pattern by comparing it against the text from RIGHT to LEFT, and on a mismatch uses a precomputed bad-character table — the rightmost position of each pattern character — to shift the pattern forward by several positions in one jump. In practice this makes it sub-linear: it skips over large sections of text that can't possibly match.
How Boyer-Moore Works
- Precompute the bad-character table: for each character, its rightmost index in the pattern.
- Align the pattern with the text and compare from the pattern's rightmost character backward.
- On a mismatch at text position i (character c), shift the pattern so its rightmost occurrence of c lines up with i — or by 1 if c is not in the pattern (use the max with a safe 1).
- On a full match, record the position and shift the pattern forward by 1 to keep searching.
- The good-suffix rule can add an even larger shift based on the already-matched suffix.
Boyer-Moore Worked Example
Input: {text: HERE IS A SIMPLE EXAMPLE, pattern: EXAMPLE}
Align 'EXAMPLE' at the start of 'HERE IS A SIMPLE EXAMPLE'. Compare right-to-left: at text[6] = 'A'... the pattern shifts several positions per mismatch using the bad-character table, skipping most of 'HERE IS A SIMPLE'. It finally aligns over 'EXAMPLE' near the end and matches fully at index 17 — far fewer comparisons than a naive left-to-right scan.
def kmp_search(text, pat):
lps = [0] * len(pat)
j = 0
for i in range(1, len(pat)):
while j > 0 and pat[i] != pat[j]:
j = lps[j - 1]
if pat[i] == pat[j]:
j += 1
lps[i] = j
out = []
j = 0
for i, c in enumerate(text):
while j > 0 and c != pat[j]:
j = lps[j - 1]
if c == pat[j]:
j += 1
if j == len(pat):
out.append(i - j + 1)
j = lps[j - 1]
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Boyer-Moore Time & Space Complexity
When to Use Boyer-Moore
- Text editors' find/replace and grep-like tools.
- Virus signature scanning across many files.
- DNA sequence pattern matching.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.