String Matching Algorithms
Go beyond brute force substring search with KMP's prefix function, the Z-algorithm and Rabin-Karp rolling hashes.
Advanced · about 6 hours · difficulty 4/5
Learn first: Array and String Fundamentals, Modular Arithmetic and Counting
Naive substring search compares the pattern at every position, costing O(n * m). Specialised algorithms find all occurrences in O(n + m). These are asked less often than core patterns but appear in harder rounds and contests.
KMP and the prefix function
The prefix function pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix. When a mismatch happens, KMP jumps using pi instead of restarting, so no character of the text is examined more than a constant number of times. Trick: compute pi on pattern + "#" + text and every position where pi equals the pattern length is a match.
Z-algorithm
z[i] is the length of the longest substring starting at i that matches a prefix of the string. It solves the same matching problem and is often easier to reason about.
Rabin-Karp rolling hash
Treat a string as a number in base b modulo a large prime. Sliding the window updates the hash in O(1). Hash equality suggests a match; verify or use double hashing to avoid collisions. Rolling hashes also solve "longest duplicate substring" when combined with binary search.
Also useful
Palindromes: expand around centre (O(n^2)) is usually enough; Manacher's algorithm gives O(n).
Good enough to move on: you can implement the prefix function and explain what pi means for a small example like "aabaaab".
Key concepts
- Prefix function and KMP
- Z-algorithm
- Rabin-Karp rolling hash
- Expand around centre palindromes
- Manacher's algorithm
- Double hashing against collisions
Mini project
Implement KMP, Z-function and Rabin-Karp and cross-check them on random strings, then solve: Find the Index of the First Occurrence, Repeated Substring Pattern, Shortest Palindrome, Longest Palindromic Substring, and Longest Happy Prefix.
Check yourself
What does pi[i] represent in KMP, and why does it guarantee the text pointer never moves backwards?
Free resources
- Prefix function and KMP (cp-algorithms)
- Z-function (cp-algorithms)
- String hashing (cp-algorithms)