1. Gyanastra
  2. Algorithms
  3. String Matching with a Finite Automaton and Boyer-Moore
  4. The problem, stated precisely
Free lesson, no account needed 7 min read

Algorithms · String Matching with a Finite Automaton and Boyer-Moore

The problem, stated precisely

We are given a text T[1..n]T[1..n] and a pattern P[1..m]P[1..m], both over a finite alphabet Σ\Sigma of size ∣Σ∣=σ|\Sigma| = \sigma. We want every shift ss with 0≤s≤n−m0 \le s \le n-m such that

T[s+1…s+m]=P[1…m].T[s+1 \ldots s+m] = P[1 \ldots m].

Each such ss is a valid shift; the others are invalid. Throughout, indices are 1-based (the CLRS convention). A question may label an alignment by its offset ss or by the 1-based start position s+1s+1, so read the options carefully; when it asks "how many comparisons", only the count matters.

The naive algorithm tries every shift and compares up to mm characters: Θ((n−m+1)m)\Theta((n-m+1)m) worst case, which is Θ(nm)\Theta(nm) when m≤n/2m \le n/2. Everything below is an attempt to beat that.


2.1 The core idea

Scan the text left to right exactly once, and after reading T[1..i]T[1..i] keep only one number: the length of the longest prefix of PP that is a suffix of what we have read so far. That number is the state. When the state reaches mm, we have found a match ending at position ii.

2.2 Definitions

A finite automaton for pattern PP is a 5-tuple (Q,q0,A,Σ,δ)(Q, q_0, A, \Sigma, \delta):

SymbolMeaning
Q={0,1,…,m}Q = \{0,1,\ldots,m\}states; state kk means "the last kk characters read equal P[1..k]P[1..k]"
q0=0q_0 = 0start state
A={m}A = \{m\}only accepting state
Σ\Sigmathe alphabet
δ:Q×Σ→Q\delta: Q \times \Sigma \to Qtransition function

The transition function is defined by the suffix function:

δ(q,a)=σ(P[1..q] a)\delta(q,a) = \sigma(P[1..q]\,a)

where σ(x)\sigma(x) is the length of the longest prefix of PP that is a suffix of the string xx. Equivalently, for state qq and character aa:

δ(q,a)=max⁡{ k:0≤k≤m and P[1..k] is a suffix of P[1..q] a }.\delta(q,a) = \max\{\,k : 0 \le k \le m \text{ and } P[1..k] \text{ is a suffix of } P[1..q]\,a\,\}.

Note the subtlety: δ(q,a)\delta(q,a) is not simply q+1q+1. It is q+1q+1 only when P[q+1]=aP[q+1] = a; otherwise the automaton must "fall back" to the longest prefix that still matches, which is exactly what σ\sigma computes.

2.3 Preprocessing: building the table in O(mσ)O(m\sigma)

The straightforward construction (CLRS, procedure COMPUTE-TRANSITION-FUNCTION) fills a table of size (m+1)×σ(m+1)\times\sigma:

for q = 0 to m:
    for each a in Sigma:
        k = min(m, q+1)
        while k > 0 and P[1..k] is not a suffix of P[1..q]a:
            k = k - 1                    # try a shorter prefix
        delta[q][a] = k

There are (m+1)σ(m+1)\sigma cells, the while loop runs up to m+1m+1 times per cell, and each suffix test costs O(m)O(m), so this version takes O(m3σ)O(m^3\sigma) time (the bound CLRS states). The table can be built in O(mσ)O(m\sigma) by reusing the KMP prefix function π\pi (longest proper border of P[1..q]P[1..q]): for q<mq<m with P[q+1]=aP[q+1]=a set δ(q,a)=q+1\delta(q,a)=q+1; otherwise set δ(q,a)=δ(π[q],a)\delta(q,a)=\delta(\pi[q],a) for q>0q>0 (and δ(0,a)=0\delta(0,a)=0 when P[1]≠aP[1]\ne a). Quote O(mσ)O(m\sigma) for the optimised construction, O(m3σ)O(m^3\sigma) for the plain CLRS procedure, and note that the table occupies Θ(mσ)\Theta(m\sigma) space.

2.4 Matching: O(n)O(n)

q = 0
for i = 1 to n:
    q = delta[q][T[i]]
    if q == m:
        print "match ends at i", shift = i - m

Each text character causes exactly one table lookup, so matching is Θ(n)\Theta(n) — independent of mm. Total: Θ(mσ)+Θ(n)\Theta(m\sigma) + \Theta(n).

2.5 Worked example: P=P = `ababa`, Σ={a,b}\Sigma = \{a,b\}

Here m=5m = 5, so states are 0,1,2,3,4,50,1,2,3,4,5. Let us compute every cell by hand. Write P[1..5]=a,b,a,b,aP[1..5] = a,b,a,b,a.

Fill every cell from the definition δ(q,a)=max⁡{k:P[1..k] is a suffix of P[1..q]a}\delta(q,a)=\max\{k: P[1..k] \text{ is a suffix of } P[1..q]a\} (never assume δ(q,a)=q+1\delta(q,a)=q+1). The classic trap is δ(2,b)\delta(2,b): the string read is abb, and no non-empty prefix of ababa is a suffix of abb, so the value is 00.

Row q=0q=0: string is just aa or bb.

  • aa: suffixes a,ε; a``§M11§ ✓ → 1.
  • bb: b not a prefix → 0.

Row q=1q=1 (prefix read a):

  • aa → string aa: suffixes aa,a,ε. aa not a prefix; a``§M15§ ✓ → 1.
  • bb → string ab: ab``§M17§ ✓ → 2.

Row q=2q=2 (read ab):

  • aa → aba: aba``§M20§ ✓ → 3.
  • bb → abb: abb✗, bb✗, b✗, ε✓ → 0.

Row q=3q=3 (read aba):

  • aa → abaa: abaa✗, baa✗, aa✗, a``§M24§ ✓ → 1.
  • bb → abab: abab``§M26§ ✓ → 4.

Row q=4q=4 (read abab):

  • aa → ababa``§M29§ ✓ → 5.
  • bb → ababb: ababb✗, babb✗, abb✗, bb✗, b✗, ε✓ → 0.

Row q=5q=5 (read ababa, full match). The automaton must still be able to continue. min⁡(m,q+1)=5\min(m,q+1)=5.

  • aa → ababaa: check k=5k=5: ababa vs suffix babaa? no. k=4k=4: abab vs abaa? no. k=3k=3: aba vs baa? no. k=2k=2: ab vs aa? no. k=1k=1: a vs a ✓ → 1.
  • bb → ababab: k=5k=5: ababa vs babab? no. k=4k=4: abab vs abab ✓ → 4.

Transition table δ(q,a)\delta(q,a) for ababa:

qq \ aaab
010
112
230
314
450
514

Sanity check on the diagonal: δ(q,P[q+1])=q+1\delta(q, P[q+1]) = q+1 for q<5q<5: δ(0,a)=1\delta(0,a)=1 ✓, δ(1,b)=2\delta(1,b)=2 ✓, δ(2,a)=3\delta(2,a)=3 ✓, δ(3,b)=4\delta(3,b)=4 ✓, δ(4,a)=5\delta(4,a)=5 ✓. Good.

2.6 Running the automaton on a text

Take T=T = aabababaa, n=9n=9. Track state qq after each character:

iiT[i]T[i]old qqδ(q,T[i])\delta(q,T[i])new qqmatch?
1a011
2a111
3b122
4a233
5b344
6a455yes, ends at 6, shift 6−5=16-5=1
7b544
8a455yes, ends at 8, shift 8−5=38-5=3
9a511

Verify by hand: T[2..6]=T[2..6]= ababa ✓ (shift 1: the match starts at position 2). T[4..8]=T[4..8]= ababa ✓ (shift 3). No other occurrence. The automaton found both with 9 lookups, no backtracking.


Pages 1–2 of 2