Algorithms · Visualized

String Matching

String Matching

Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.

Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.

📖 Family Introduction

String Matching

Find a pattern inside text in linear time — preprocessing makes the scan skip intelligently.

String matching finds all occurrences of a pattern in a text. Naive comparison restarts from scratch after every mismatch and costs O(n·m). The whole family’s trick is preprocessing the pattern (or the text) into a small table so that, after a mismatch, the scan shifts by more than one without re-reading characters — KMP via its prefix function π, Boyer–Moore via bad-character/good-suffix jumps, Rabin–Karp via a rolling hash that compares fingerprints first and characters only on hits.

The general recipe

  1. Preprocess the pattern: KMP builds π[i] = length of the longest proper prefix of p[0..i] that is also its suffix.
  2. Scan the text with a pattern pointer; on match, advance both.
  3. On mismatch, fall back using the table (KMP/Boyer–Moore) or slide by hash comparison (Rabin–Karp) instead of restarting.
  4. Record a hit when the pattern pointer reaches the pattern’s end.
  5. Multi-pattern searches (Aho–Corasick) merge all patterns into one automaton and scan the text once.

Vocabulary you'll meet everywhere here

Prefix function π
KMP’s table: longest proper prefix that is also a suffix for each prefix of the pattern
Rolling hash
a fingerprint of the current window updated in O(1) as the window slides (Rabin–Karp)
Spurious hit
a hash match whose characters differ — always verify with a direct comparison
Z-array
for each position, the longest substring starting there matching the text’s prefix (Z-algorithm)
Sublinear
Boyer–Moore often skips so much it examines fewer than n characters in practice

Where this family shows up

  • Text editors’ find, plagiarism and document similarity scanning
  • Bioinformatics motif search over DNA strings
  • Intrusion detection and keyword filtering over streams (Aho–Corasick), longest palindromic substring (Manacher)

Common pitfalls

  • Restarting the pattern pointer to 0 on every mismatch silently reintroduces the O(n·m) naive cost
  • Trusting hashes blindly: Rabin–Karp must verify candidate hits character-by-character
  • Off-by-one conventions in π/z tables (0- vs 1-indexed) are the most common implementation bug
  • Overlapping occurrences: make sure your post-hit shift still counts them when the problem wants them
Python · String Matching in Code
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 out

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.