Algorithms · UGC NET: Selected and Advanced Algorithms
String Matching
Overview
String matching is the problem of finding all occurrences of a pattern of length inside a text of length , with .
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 ; pattern is ; alphabet is with size . A valid shift with means .
- 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 when a long prefix matches before a mismatch.
- Rabin-Karp uses a rolling hash modulo a prime with radix (for decimal digits, ). A hash match is verified character-by-character. A spurious hit is a hash match where the strings are not equal.
Worst case is ; expected time is . - KMP preprocesses the pattern into a prefix function , also called the failure function. Using 1-indexed CLRS convention, is the length of the longest proper prefix of that is also a suffix of .
Proper means length less than , so and . Preprocessing is ; matching is ; total is . - Finite-Automaton matcher builds a transition function for states and every character . State is the length of the longest prefix of that is a suffix of the text read so far.
Preprocessing is ; matching is . - 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 ; worst-case matching with both heuristics; best case . Bad-character alone can be worst case. - Shift is 0-indexed: shift aligns with . Pattern positions are 1-indexed. Keep this convention throughout.
How it works
-
Naive algorithm. For each shift to , compare with from left to right. Stop the current comparison at the first mismatch. Report on a full match. The reason is simple: every possible alignment is tested.
-
Rabin-Karp algorithm. Compute the pattern hash and the first window hash using . If , verify the actual characters. Update the window hash in by removing the leading digit, multiplying by , adding the new trailing digit, and reducing modulo . Use a prime to reduce collisions. A collision still requires verification, so worst case is .
-
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 piThen 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, is the number of characters already matched. The next possible alignment is the longest proper prefix that is also a suffix, so set and retry the same text character. Do not advance during the fallback. If is written as the current pattern position, the equivalent fallback is .
-
Finite-Automaton algorithm. Define and is a suffix of . Build the table for all states and all . Then set and for each text character , set . If , report shift . Each text character takes after preprocessing.
-
Boyer-Moore algorithm. Align the pattern and compare with the text window from right to left. On a mismatch at pattern position with text character :
- Bad-character shift: let be the rightmost position in with , or if absent. Use , at least .
- Good-suffix shift: the already matched suffix must align with its next occurrence in or with a prefix of ; this is precomputed in .
- Shift by . The max is safe and skips more characters.
Drawing the diagram…
Formulas
- Naive worst case: .
- Rabin-Karp hash: .
- Pattern hash: .
- Rolling update: .
- KMP prefix function: and , with .
- KMP total time: .
- Finite-automaton transition: and is a suffix of .
- Finite-automaton total time: .
- Boyer-Moore bad-character shift: , where or .
- Boyer-Moore final shift: .
Worked examples
Example 1: Naive worst case. Let () and (). Shifts are , so shifts. At each shift, the first three characters match and the fourth comparison fails, so each shift uses comparisons. Total .
This is the classic worst-case input for Naive.
Example 2: KMP prefix function. For , 1-indexed:
| Longest proper prefix = suffix | |||
|---|---|---|---|
| 1 | a | none | 0 |
| 2 | aa | "a" | 1 |
| 3 | aab | none | 0 |
| 4 | aaba | "a" | 1 |
| 5 | aabaa | "aa" | 2 |
| So and . For , , so , , , . |
Example 3: Rabin-Karp spurious hit. Let , , . Pattern hash . A text window has hash . Hashes match, but , so this is a spurious hit; verify and discard.
Also, with , has hash ; a window has hash , another spurious hit. For , , the leading-digit factor is .
Example 4: Finite-automaton transition table. For over :
| 0 | 1 | 0 |
| 1 | 1 | 2 |
| 2 | 3 | 0 |
| 3 | 1 | 4 |
| 4 | 3 | 0 |
| For instance, at state the matched prefix is . Appending gives , whose longest prefix of that is also a suffix is of length , so . Appending gives , whose longest such prefix is empty, so . |
Example 5: Boyer-Moore shift. Let () and the aligned text window be . Compare right-to-left:
- : , text : match.
- : , text : match.
- : , text : mismatch.
The matched suffix is (positions ). Bad-character: is absent before position , so . Good-suffix: also occurs at positions , so . Shift . Move the pattern right by positions.
Comparison
| Algorithm | Preprocessing | Matching time | Worst-case total | Direction | Key idea |
|---|---|---|---|---|---|
| Naive | left-to-right | check every shift | |||
| Rabin-Karp | expected | due to spurious hits | left-to-right | rolling hash plus verification | |
| KMP | left-to-right | prefix function fallback | |||
| Finite Automaton | left-to-right | DFA state tracks longest prefix | |||
| Boyer-Moore | worst with both heuristics | standard exam model | right-to-left | bad-character and good-suffix skips |
| Term | Hash equal? | Characters equal? | Action |
|---|---|---|---|
| Genuine match | yes | yes | report occurrence |
| Spurious hit | yes | no | discard after verification |
| Hash miss | no | irrelevant | skip verification |
| Concept | KMP | Finite-automaton |
|---|---|---|
| Meaning | longest proper prefix of that is suffix of | next state after appending character |
| Storage | ||
| Build time | ||
| Use | fallback on mismatch | direct transition per text character |
Revision summary
- ; shifts are ; pattern positions are in CLRS convention.
- Naive worst case is when many characters match before a mismatch.
- Rabin-Karp: expected , worst ; spurious hit means hash equal but strings unequal.
- Rolling hash update is : subtract leading contribution, multiply by , add trailing digit, reduce mod .
- KMP: , , and is the longest proper prefix that is also a suffix.
- KMP mismatch: in CLRS length form, set ; if is the current pattern position, set .
- KMP total is ; Finite-Automaton total is .
- 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 in Rabin-Karp to reduce spurious hits.
- Finite-automaton matching is after preprocessing because each character uses one table lookup.
- For P=abababab, prefix values are at positions .
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 for patterns such as
aabaaorabababab; remember proper prefix and . - Rabin-Karp numeric questions: compute hash mod , detect a spurious hit, and compute .
- Match List-I/List-II questions: know preprocessing and worst-case matching times; Rabin-Karp worst case is , not .
- Statement/Assertion questions: KMP fallback does not advance the text pointer; ; finite-automaton matching is after preprocessing.
- Boyer-Moore questions: compare right-to-left; bad-character shift must be at least ; final shift is max of bad-character and good-suffix.
- Code/order questions: KMP while-loop uses in CLRS form; do not increment unless characters match.
- Traps: 0-indexed vs 1-indexed, shift vs , vs , 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 , 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 .
- Build a finite-automaton transition table for a small pattern and alphabet.
- Explain finite-automaton preprocessing and matching .
- 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 .
Attempt the sub-topic test first, then the subject test.