String Algorithms
Pattern matching in linear time with KMP, Rabin-Karp and the Z-algorithm, plus Manacher's palindromes and suffix structures.
Pattern matching — find all occurrences of a pattern P (length m) in a text T (length n) — underlies grep, editors' find, intrusion detection, DNA search and plagiarism checkers.
The naive approach tries every starting position and compares up to m characters: O(n·m) worst case (e.g. T = "aaaa…a", P = "aaab"). The algorithms below are O(n + m).
KMP (Knuth-Morris-Pratt)
When a mismatch happens after matching some characters, the naive method throws that knowledge away. KMP precomputes, for each prefix of P, the length of the longest proper prefix that is also a suffix (the LPS or failure array). On mismatch, it jumps to that length instead of restarting — the text pointer never moves backward.
| P | a | b | a | b | c | a | b | a | b |
|---|---|---|---|---|---|---|---|---|---|
| LPS | 0 | 0 | 1 | 2 | 0 | 1 | 2 | 3 | 4 |
int[] lps(String p) {
int[] lps = new int[p.length()];
for (int i = 1, len = 0; i < p.length(); ) {
if (p.charAt(i) == p.charAt(len)) lps[i++] = ++len;
else if (len > 0) len = lps[len - 1]; // fall back, don't advance i
else lps[i++] = 0;
}
return lps;
}
List<Integer> kmpSearch(String t, String p) {
int[] lps = lps(p);
List<Integer> hits = new ArrayList<>();
for (int i = 0, j = 0; i < t.length(); ) {
if (t.charAt(i) == p.charAt(j)) {
i++; j++;
if (j == p.length()) { hits.add(i - j); j = lps[j - 1]; }
} else if (j > 0) j = lps[j - 1];
else i++;
}
return hits;
}def build_lps(p):
lps, length, i = [0] * len(p), 0, 1
while i < len(p):
if p[i] == p[length]:
length += 1
lps[i] = length
i += 1
elif length:
length = lps[length - 1] # fall back
else:
i += 1
return lps
def kmp_search(t, p):
lps, hits, j = build_lps(p), [], 0
for i, c in enumerate(t):
while j and c != p[j]:
j = lps[j - 1]
if c == p[j]:
j += 1
if j == len(p):
hits.append(i - j + 1)
j = lps[j - 1]
return hitsfunction buildLps(p: string): number[] {
const lps = new Array(p.length).fill(0);
for (let i = 1, len = 0; i < p.length; ) {
if (p[i] === p[len]) lps[i++] = ++len;
else if (len > 0) len = lps[len - 1];
else lps[i++] = 0;
}
return lps;
}
function kmpSearch(t: string, p: string): number[] {
const lps = buildLps(p), hits: number[] = [];
let j = 0;
for (let i = 0; i < t.length; i++) {
while (j > 0 && t[i] !== p[j]) j = lps[j - 1];
if (t[i] === p[j] && ++j === p.length) { hits.push(i - j + 1); j = lps[j - 1]; }
}
return hits;
}Rabin-Karp (rolling hash)
Hash the pattern, then slide a window over the text, updating the window's hash in O(1) by removing the outgoing character and adding the incoming one. Only compare characters when hashes match.
Average O(n + m); worst O(n·m) with many collisions (use a large prime modulus or two hashes). Rolling hashes shine for many patterns at once, longest duplicate substring (with binary search on length), and plagiarism detection.
List<Integer> rabinKarp(String t, String p) {
final long B = 256, M = 1_000_000_007L;
int n = t.length(), m = p.length();
List<Integer> hits = new ArrayList<>();
if (m > n) return hits;
long hp = 0, ht = 0, pow = 1;
for (int i = 0; i < m; i++) {
hp = (hp * B + p.charAt(i)) % M;
ht = (ht * B + t.charAt(i)) % M;
if (i > 0) pow = pow * B % M;
}
for (int i = 0; ; i++) {
if (hp == ht && t.regionMatches(i, p, 0, m)) hits.add(i); // verify on hash match
if (i + m >= n) break;
ht = ((ht - t.charAt(i) * pow % M + M) * B + t.charAt(i + m)) % M;
}
return hits;
}def rabin_karp(t, p, B=256, M=1_000_000_007):
n, m = len(t), len(p)
if m > n:
return []
pow_ = pow(B, m - 1, M)
hp = ht = 0
for i in range(m):
hp = (hp * B + ord(p[i])) % M
ht = (ht * B + ord(t[i])) % M
hits = []
for i in range(n - m + 1):
if hp == ht and t[i:i + m] == p:
hits.append(i)
if i + m < n:
ht = ((ht - ord(t[i]) * pow_) * B + ord(t[i + m])) % M
return hitsfunction rabinKarp(t: string, p: string): number[] {
const B = 256n, M = 1_000_000_007n, n = t.length, m = p.length;
if (m > n) return [];
let hp = 0n, ht = 0n, pow = 1n;
for (let i = 0; i < m; i++) {
hp = (hp * B + BigInt(p.charCodeAt(i))) % M;
ht = (ht * B + BigInt(t.charCodeAt(i))) % M;
if (i > 0) pow = (pow * B) % M;
}
const hits: number[] = [];
for (let i = 0; i + m <= n; i++) {
if (hp === ht && t.startsWith(p, i)) hits.push(i);
if (i + m < n)
ht = (((ht - BigInt(t.charCodeAt(i)) * pow) % M + M) * B + BigInt(t.charCodeAt(i + m))) % M;
}
return hits;
}Z-algorithm
Z[i] = length of the longest substring starting at i that matches a prefix of the string. Compute Z for P + "$" + T; every position where Z[i] == m is a match. O(n + m), and often simpler to remember than KMP.
Manacher's algorithm
Finds the longest palindromic substring in O(n) by reusing palindrome radii mirrored around the current rightmost palindrome's centre. In interviews, the O(n²) expand-around-centre approach (2n − 1 centres) is usually acceptable.
String longestPalindrome(String s) {
int best = 0, start = 0;
for (int c = 0; c < 2 * s.length() - 1; c++) {
int l = c / 2, r = l + c % 2; // odd and even centres
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }
if (r - l - 1 > best) { best = r - l - 1; start = l + 1; }
}
return s.substring(start, start + best);
}def longest_palindrome(s):
best = (0, 0)
for c in range(2 * len(s) - 1):
l, r = c // 2, c // 2 + c % 2
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1; r += 1
if r - l - 1 > best[1] - best[0]:
best = (l + 1, r)
return s[best[0]:best[1]]function longestPalindrome(s: string): string {
let start = 0, best = 0;
for (let c = 0; c < 2 * s.length - 1; c++) {
let l = c >> 1, r = l + (c & 1);
while (l >= 0 && r < s.length && s[l] === s[r]) { l--; r++; }
if (r - l - 1 > best) { best = r - l - 1; start = l + 1; }
}
return s.slice(start, start + best);
}Suffix structures (brief)
- Suffix array — all suffixes sorted, O(n log n) to build; with the LCP array it answers longest repeated substring, number of distinct substrings and multi-pattern search.
- Suffix automaton / suffix tree — linear-size structures supporting substring queries in O(m). Used in bioinformatics and compression.
- Aho-Corasick — a trie of many patterns plus KMP-like failure links: find all occurrences of thousands of keywords in one pass (antivirus scanners,
grep -F).
- Naive matching is O(nm); KMP, Z and Rabin-Karp are O(n + m).
- KMP: LPS array means the text pointer never moves back.
- Rabin-Karp: O(1) rolling hash updates; verify on hash match.
- Palindromes: expand around centre (O(n²)) or Manacher (O(n)).
QFind the shortest palindrome formed by adding characters in front of s.hard
Compute the LPS (KMP failure) array of s + "#" + reverse(s). The last LPS value is the length of the longest palindromic prefix of s; prepend the reverse of the remaining suffix. O(n).
QRepeated substring pattern: is s made of a repeated substring?easy
Check whether s occurs in (s + s) with the first and last characters removed. Or with KMP: let L = lps[n−1]; the answer is true if L > 0 and n % (n − L) == 0.