Learn / Strings

Pattern matching

Finding a pattern of length m in a text of length n naively costs O(n × m). KMP and the Z-function reuse what earlier comparisons already proved, so they never move backwards in the text and run in O(n + m). Rabin-Karp compares rolling hashes instead, and Boyer-Moore skips ahead using the last character that failed.

How to recognise it

  • Find where (or whether) one string appears inside another, possibly many times.
  • The question is about prefixes that are also suffixes (borders), or the longest palindromic prefix.
  • n and m are both large, so O(n × m) is too slow.

The idea in one picture

Slide the pattern along the text like a ruler. The naive way, after a mismatch, slides the ruler one step and starts comparing from scratch. The smart ways remember what the last attempt proved, and jump the ruler as far as that proof allows.

Four methods

MethodKey ideaTimeProblems here
KMPlps: after a mismatch, keep the longest part that still matchesO(n + m)First Occurrence, Shortest Palindrome, Happy Prefix
Z-functionz[i]: how far s[i..] matches the start of sO(n + m)Z function
Rabin-Karprolling hash of each window, check letters on a hash matchO(n + m) expectedRabin Karp
Boyer-Moore (bad character)compare from the right, shift past the bad characteroften sublinear, O(n × m) worstBoyer Moore

Template: the KMP prefix function

lps = array of m zeros, len = 0, i = 1
while i < m:
    if p[i] == p[len]: len = len + 1; lps[i] = len; i = i + 1
    else if len > 0: len = lps[len - 1]     # try the next shorter border
    else: lps[i] = 0; i = i + 1

The same function solves border questions directly: lps[m - 1] is the longest prefix that is also a suffix. Running it on s + "#" + reverse(s) gives the longest palindromic prefix of s.

Common mistakes

  • Moving the text index backwards after a mismatch, which brings back the O(n × m) cost.
  • Forgetting the separator in pattern + "$" + text, so matches run across the join.
  • Trusting a hash match without comparing the letters.
  • Off-by-one errors when turning a position in the joined string back into a text index.

Problems

0 of 6 solved

Check yourself

In KMP, what does lps[i] store?

What is z[i] in the Z-function of a string s?

Why does Rabin-Karp compare the letters after the hashes match?

The longest happy prefix of "ababab" is...