Strings

String Algorithms

Pattern matching, hashing, palindromes and suffix structures.

Naive String Matching
▶ viz

Try every alignment of the pattern against the text and compare character by character.

O(n · m) · O(1) space
Knuth–Morris–Pratt (KMP)
▶ viz

Linear-time pattern matching that never re-reads text characters, using a precomputed failure (LPS) table of the pattern.

O(n + m) · O(m) space
Rabin–Karp
▶ viz

Compare a rolling hash of each text window with the pattern hash and verify only on hash hits.

O(n · m) · O(1) space
Z-Algorithm
▶ viz

Compute for every position the length of the longest substring starting there that matches a prefix of the string, in linear time.

O(n + m) · O(n + m) space
Manacher's Algorithm
▶ viz

Compute the palindrome radius around every center in O(n) by reusing mirrored radii inside the rightmost known palindrome.

O(n) · O(n) space
Rolling Hash (Polynomial Hashing)
▶ viz

Precompute prefix hashes so the hash of any substring — and hence substring equality — can be evaluated in O(1).

O(n) · O(n) space
Aho–Corasick
▶ viz

Search a text for every word of a dictionary simultaneously by walking a trie augmented with KMP-style failure links.

O(n + L + z) · O(L · σ) space
Suffix Array

Sort all suffixes of a string by index; with the LCP array it answers substring search, distinct-substring counts and longest-repeat queries.

O(n log² n) · O(n) space
Suffix Tree

A compressed trie of all suffixes of a string; answers substring search in O(m), longest repeat and distinct-substring counts directly from its structure.

O(n) · O(n · σ) space