1. Gyanastra
  2. Algorithms
  3. UGC NET: Selected and Advanced Algorithms
  4. String Matching
Free lesson, no account needed 10 min read 23 practice questions after it

Algorithms · UGC NET: Selected and Advanced Algorithms

String Matching

Overview

String matching is the problem of finding all occurrences of a pattern PP of length mm inside a text TT of length nn, with m≤nm \le n.
It belongs to the "Selected and Advanced Algorithms" area because it introduces preprocessing, hashing, automata, amortized analysis, and heuristic skipping.
Before studying it, know arrays, loops, asymptotic notation, modular arithmetic, and the idea of a finite automaton.
UGC NET expects you to compare Naive, Rabin-Karp, Knuth-Morris-Pratt, Finite-Automaton, and Boyer-Moore algorithms by preprocessing time, matching time, worst-case behaviour, direction of comparison, and data structures used.

Key concepts

  • Text is T[1..n]T[1..n]; pattern is P[1..m]P[1..m]; alphabet is Σ\Sigma with size ∣Σ∣|\Sigma|. A valid shift ss with 0≤s≤n−m0 \le s \le n-m means P[1..m]=T[s+1..s+m]P[1..m] = T[s+1..s+m].
  • Exact string matching reports every valid shift. Approximate matching is outside this lesson.
  • Naive string matcher checks every shift left-to-right and has no preprocessing. Worst case is O((n−m+1)m)=O(nm)O((n-m+1)m)=O(nm) when a long prefix matches before a mismatch.
  • Rabin-Karp uses a rolling hash modulo a prime qq with radix d=∣Σ∣d=|\Sigma| (for decimal digits, d=10d=10). A hash match is verified character-by-character. A spurious hit is a hash match where the strings are not equal.
    Worst case is O(nm)O(nm); expected time is O(n+m)O(n+m).
  • KMP preprocesses the pattern into a prefix function π[1..m]\pi[1..m], also called the failure function. Using 1-indexed CLRS convention, π[q]\pi[q] is the length of the longest proper prefix of P[1..q]P[1..q] that is also a suffix of P[1..q]P[1..q].
    Proper means length less than qq, so π[q]<q\pi[q] < q and π[1]=0\pi[1]=0. Preprocessing is O(m)O(m); matching is O(n)O(n); total is O(n+m)O(n+m).
  • Finite-Automaton matcher builds a transition function δ(q,a)\delta(q,a) for states 0..m0..m and every character a∈Σa \in \Sigma. State qq is the length of the longest prefix of PP that is a suffix of the text read so far.
    Preprocessing is O(m∣Σ∣)O(m|\Sigma|); matching is O(n)O(n).
  • Boyer-Moore compares the pattern with the text right-to-left. It uses the bad-character heuristic and good-suffix heuristic and shifts by the maximum safe amount.
    Standard exam model: preprocessing O(m+∣Σ∣)O(m+|\Sigma|); worst-case matching O(n+m)O(n+m) with both heuristics; best case O(n/m)O(n/m). Bad-character alone can be O(nm)O(nm) worst case.
  • Shift is 0-indexed: shift ss aligns P[1..m]P[1..m] with T[s+1..s+m]T[s+1..s+m]. Pattern positions are 1-indexed. Keep this convention throughout.

How it works

  1. Naive algorithm. For each shift s=0s=0 to n−mn-m, compare P[1..m]P[1..m] with T[s+1..s+m]T[s+1..s+m] from left to right. Stop the current comparison at the first mismatch. Report ss on a full match. The reason is simple: every possible alignment is tested.

  2. Rabin-Karp algorithm. Compute the pattern hash pp and the first window hash tt using h(s)=(∑j=1mT[s+j−1] dm−j) mod qh(s)=\left(\sum_{j=1}^{m}T[s+j-1]\,d^{m-j}\right)\bmod q. If p=tp=t, verify the actual characters. Update the window hash in O(1)O(1) by removing the leading digit, multiplying by dd, adding the new trailing digit, and reducing modulo qq. Use a prime qq to reduce collisions. A collision still requires verification, so worst case is O(nm)O(nm).

  3. KMP algorithm. First compute the prefix function. CLRS pseudocode:

    COMPUTE-PREFIX-FUNCTION(P)
    m = P.length
    pi[1] = 0
    k = 0
    for q = 2 to m
        while k > 0 and P[k+1] != P[q]
            k = pi[k]
        if P[k+1] == P[q]
            k = k + 1
        pi[q] = k
    return pi
    

    Then match:

    KMP-MATCHER(T, P)
    n = T.length
    m = P.length
    pi = COMPUTE-PREFIX-FUNCTION(P)
    q = 0
    for i = 1 to n
        while q > 0 and P[q+1] != T[i]
            q = pi[q]
        if P[q+1] == T[i]
            q = q + 1
        if q == m
            print "Pattern occurs with shift" i - m
            q = pi[q]
    

    On a mismatch, qq is the number of characters already matched. The next possible alignment is the longest proper prefix that is also a suffix, so set q=π[q]q=\pi[q] and retry the same text character. Do not advance ii during the fallback. If qq is written as the current pattern position, the equivalent fallback is q=π[q−1]q=\pi[q-1].

  4. Finite-Automaton algorithm. Define δ(q,a)=max⁡{k:0≤k≤m\delta(q,a)=\max\{k:0\le k\le m and P[1..k]P[1..k] is a suffix of P[1..q]a}P[1..q]a\}. Build the table for all states 0..m0..m and all a∈Σa\in\Sigma. Then set q=0q=0 and for each text character T[i]T[i], set q=δ(q,T[i])q=\delta(q,T[i]). If q=mq=m, report shift i−mi-m. Each text character takes O(1)O(1) after preprocessing.

  5. Boyer-Moore algorithm. Align the pattern and compare P[m],P[m−1],…P[m],P[m-1],\dots with the text window from right to left. On a mismatch at pattern position jj with text character cc:

    • Bad-character shift: let last[c]last[c] be the rightmost position <j<j in PP with P[last[c]]=cP[last[c]]=c, or 00 if absent. Use shiftbc=j−last[c]shift_{bc}=j-last[c], at least 11.
    • Good-suffix shift: the already matched suffix P[j+1..m]P[j+1..m] must align with its next occurrence in PP or with a prefix of PP; this is precomputed in O(m)O(m).
    • Shift by max⁡(shiftbc,shiftgs)\max(shift_{bc}, shift_{gs}). The max is safe and skips more characters.
Figure. Notice that on a mismatch with q > 0, the flow sets q = pi[q] and retries the same text character; q increments only when P[q+1] equals T[i]. If q equals m, it reports shift i−m and sets q = pi[q] before the next i.

Formulas

  • Naive worst case: (n−m+1)m=O(nm)(n-m+1)m = O(nm).
  • Rabin-Karp hash: h(s)=(∑j=1mT[s+j−1] dm−j) mod qh(s)=\left(\sum_{j=1}^{m}T[s+j-1]\,d^{m-j}\right)\bmod q.
  • Pattern hash: p=(∑j=1mP[j] dm−j) mod qp=\left(\sum_{j=1}^{m}P[j]\,d^{m-j}\right)\bmod q.
  • Rolling update: h(s+1)=(d(h(s)−T[s+1] dm−1)+T[s+m+1]) mod qh(s+1)=\left(d\left(h(s)-T[s+1]\,d^{m-1}\right)+T[s+m+1]\right)\bmod q.
  • KMP prefix function: π[q]=max⁡{k:0≤k<q\pi[q]=\max\{k:0\le k<q and P[1..k]=P[q−k+1..q]}P[1..k]=P[q-k+1..q]\}, with π[1]=0\pi[1]=0.
  • KMP total time: O(m+n)O(m+n).
  • Finite-automaton transition: δ(q,a)=max⁡{k:0≤k≤m\delta(q,a)=\max\{k:0\le k\le m and P[1..k]P[1..k] is a suffix of P[1..q]a}P[1..q]a\}.
  • Finite-automaton total time: O(m∣Σ∣+n)O(m|\Sigma|+n).
  • Boyer-Moore bad-character shift: shiftbc=j−last[c]shift_{bc}=j-last[c], where last[c]=max⁡{k<j:P[k]=c}last[c]=\max\{k<j:P[k]=c\} or 00.
  • Boyer-Moore final shift: shift=max⁡(shiftbc,shiftgs)shift=\max(shift_{bc},shift_{gs}).

Worked examples

Example 1: Naive worst case. Let T="aaaaaaaa"T=\text{"aaaaaaaa"} (n=8n=8) and P="aaab"P=\text{"aaab"} (m=4m=4). Shifts are s=0,1,2,3,4s=0,1,2,3,4, so 8−4+1=58-4+1=5 shifts. At each shift, the first three characters match and the fourth comparison fails, so each shift uses 44 comparisons. Total =5×4=20=(n−m+1)m=5\times4=20=(n-m+1)m.
This is the classic worst-case input for Naive.

Example 2: KMP prefix function. For P="aabaa"P=\text{"aabaa"}, 1-indexed:

qqP[1..q]P[1..q]Longest proper prefix = suffixπ[q]\pi[q]
1anone0
2aa"a"1
3aabnone0
4aaba"a"1
5aabaa"aa"2
So π=[0,1,0,1,2]\pi=[0,1,0,1,2] and π[5]=2\pi[5]=2. For P="abababab"P=\text{"abababab"}, π=[0,0,1,2,3,4,5,6]\pi=[0,0,1,2,3,4,5,6], so π[2]=0\pi[2]=0, π[4]=2\pi[4]=2, π[6]=4\pi[6]=4, π[8]=6\pi[8]=6.

Example 3: Rabin-Karp spurious hit. Let d=10d=10, q=7q=7, P="34"P=\text{"34"}. Pattern hash =(3×10+4) mod 7=34 mod 7=6=(3\times10+4)\bmod7=34\bmod7=6. A text window "41"\text{"41"} has hash (4×10+1) mod 7=41 mod 7=6(4\times10+1)\bmod7=41\bmod7=6. Hashes match, but "34"≠"41"\text{"34"}\ne\text{"41"}, so this is a spurious hit; verify and discard.
Also, with q=13q=13, P="26"P=\text{"26"} has hash 26 mod 13=026\bmod13=0; a window "39"\text{"39"} has hash 39 mod 13=039\bmod13=0, another spurious hit. For m=3m=3, q=11q=11, the leading-digit factor is 10m−1=102=100≡1(mod11)10^{m-1}=10^2=100\equiv1\pmod{11}.

Example 4: Finite-automaton transition table. For P="abab"P=\text{"abab"} over Σ={a,b}\Sigma=\{a,b\}:

qqδ(q,a)\delta(q,a)δ(q,b)\delta(q,b)
010
112
230
314
430
For instance, at state q=2q=2 the matched prefix is "ab"\text{"ab"}. Appending aa gives "aba"\text{"aba"}, whose longest prefix of PP that is also a suffix is "aba"\text{"aba"} of length 33, so δ(2,a)=3\delta(2,a)=3. Appending bb gives "abb"\text{"abb"}, whose longest such prefix is empty, so δ(2,b)=0\delta(2,b)=0.

Example 5: Boyer-Moore shift. Let P="abcab"P=\text{"abcab"} (m=5m=5) and the aligned text window be "abxab"\text{"abxab"}. Compare right-to-left:

  • j=5j=5: P[5]=bP[5]=b, text bb: match.
  • j=4j=4: P[4]=aP[4]=a, text aa: match.
  • j=3j=3: P[3]=cP[3]=c, text xx: mismatch.
    The matched suffix is "ab"\text{"ab"} (positions 4..54..5). Bad-character: xx is absent before position 33, so shiftbc=3−0=3shift_{bc}=3-0=3. Good-suffix: "ab"\text{"ab"} also occurs at positions 1..21..2, so shiftgs=4−1=3shift_{gs}=4-1=3. Shift =max⁡(3,3)=3=\max(3,3)=3. Move the pattern right by 33 positions.

Comparison

AlgorithmPreprocessingMatching timeWorst-case totalDirectionKey idea
NaiveO(1)O(1)O((n−m+1)m)O((n-m+1)m)O(nm)O(nm)left-to-rightcheck every shift
Rabin-KarpO(m)O(m)O(n+m)O(n+m) expectedO(nm)O(nm) due to spurious hitsleft-to-rightrolling hash plus verification
KMPO(m)O(m)O(n)O(n)O(n+m)O(n+m)left-to-rightprefix function fallback
Finite AutomatonO(m∣Σ∣)O(m|\Sigma|)O(n)O(n)O(m∣Σ∣+n)O(m|\Sigma|+n)left-to-rightDFA state tracks longest prefix
Boyer-MooreO(m+∣Σ∣)O(m+|\Sigma|)O(n)O(n) worst with both heuristicsO(n+m)O(n+m) standard exam modelright-to-leftbad-character and good-suffix skips
TermHash equal?Characters equal?Action
Genuine matchyesyesreport occurrence
Spurious hityesnodiscard after verification
Hash missnoirrelevantskip verification
ConceptKMP π\piFinite-automaton δ\delta
Meaninglongest proper prefix of P[1..q]P[1..q] that is suffix of P[1..q]P[1..q]next state after appending character aa
StorageO(m)O(m)O(m∣Σ∣)O(m|\Sigma|)
Build timeO(m)O(m)O(m∣Σ∣)O(m|\Sigma|)
Usefallback on mismatchdirect transition per text character

Revision summary

  • m≤nm\le n; shifts are 0..n−m0..n-m; pattern positions are 1..m1..m in CLRS convention.
  • Naive worst case is O(nm)O(nm) when many characters match before a mismatch.
  • Rabin-Karp: expected O(n+m)O(n+m), worst O(nm)O(nm); spurious hit means hash equal but strings unequal.
  • Rolling hash update is O(1)O(1): subtract leading contribution, multiply by dd, add trailing digit, reduce mod qq.
  • KMP: π[1]=0\pi[1]=0, π[q]<q\pi[q]<q, and π[q]\pi[q] is the longest proper prefix that is also a suffix.
  • KMP mismatch: in CLRS length form, set q=π[q]q=\pi[q]; if qq is the current pattern position, set q=π[q−1]q=\pi[q-1].
  • KMP total is O(n+m)O(n+m); Finite-Automaton total is O(m∣Σ∣+n)O(m|\Sigma|+n).
  • Boyer-Moore compares right-to-left; bad-character alone can give zero or negative shift, so enforce progress and use max with good-suffix.
  • Choose prime qq in Rabin-Karp to reduce spurious hits.
  • Finite-automaton matching is O(n)O(n) after preprocessing because each character uses one table lookup.
  • For P=abababab, prefix values are 0,0,1,2,3,4,5,60,0,1,2,3,4,5,6 at positions 1..81..8.

Previous-year exam insights

  • Direct concept: identify which algorithm uses prefix function, transition function, rolling hash, or right-to-left comparison.
  • Numeric prefix-function questions: compute π\pi for patterns such as aabaa or abababab; remember proper prefix and π[1]=0\pi[1]=0.
  • Rabin-Karp numeric questions: compute hash mod qq, detect a spurious hit, and compute 10m−1 mod q10^{m-1}\bmod q.
  • Match List-I/List-II questions: know preprocessing and worst-case matching times; Rabin-Karp worst case is O(nm)O(nm), not O(n+m)O(n+m).
  • Statement/Assertion questions: KMP fallback does not advance the text pointer; π[q]<q\pi[q]<q; finite-automaton matching is O(n)O(n) after preprocessing.
  • Boyer-Moore questions: compare right-to-left; bad-character shift must be at least 11; final shift is max of bad-character and good-suffix.
  • Code/order questions: KMP while-loop uses q=π[q]q=\pi[q] in CLRS form; do not increment qq unless characters match.
  • Traps: 0-indexed vs 1-indexed, shift i−mi-m vs i−m+1i-m+1, qq vs q−1q-1, and confusing average time with worst-case time.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  • State the worst-case input and comparison count for Naive string matching.
  • Compute a Rabin-Karp hash, update a window hash in O(1)O(1), and identify a spurious hit.
  • Compute the KMP prefix function for a short pattern and trace KMP matching on a short text.
  • Explain why KMP does not advance the text pointer during fallback and why total time is O(n+m)O(n+m).
  • Build a finite-automaton transition table for a small pattern and alphabet.
  • Explain finite-automaton preprocessing O(m∣Σ∣)O(m|\Sigma|) and matching O(n)O(n).
  • Trace Boyer-Moore right-to-left comparison and apply bad-character and good-suffix shifts.
  • Distinguish preprocessing, matching, and worst-case total times in a match-list question.
  • Evaluate statement/assertion questions about prefix functions, spurious hits, and Boyer-Moore shifts.
  • Use the 1-indexed CLRS convention correctly and report a match at shift i−mi-m.

Attempt the sub-topic test first, then the subject test.

Pages 1–2 of 2