String Algorithms (KMP, Z, Rolling Hash, Trie)
Find a pattern in a text in one pass without ever re-reading characters, compare substrings in constant time, and store a dictionary of words by shared prefixes.
After this lesson you will be able to
- Explain why naive substring search is O(n × m) and where the repeated work comes from.
- Compute the prefix function (borders) and use it to run KMP search in O(n + m).
- Compute the Z-function and use it for pattern search.
- Use a polynomial rolling hash to compare substrings, and say when a hash match must be verified.
- Build a trie, and use it for membership, prefix queries and prefix counts.
Before you start. Arrays (indexing and slicing) and Sets & Dictionaries (hashing). Comfort with for and while loops over indices.