String Algorithms

Pattern matching in linear time with KMP, Rabin-Karp and the Z-algorithm, plus Manacher's palindromes and suffix structures.

Advanced 3 min readLesson 16 of 18 Interview Q&A

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.

Pababcabab
LPS001201234
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;
}

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.

H(si+1..i+m)=(H(si..i+m−1)−si⋅Bm−1)⋅B+si+m(modM)H(s_{i+1..i+m}) = \big(H(s_{i..i+m-1}) - s_i \cdot B^{m-1}\big)\cdot B + s_{i+m} \pmod{M}

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;
}

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.

Longest palindromic substring — expand around centre, O(n²)
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);
}

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).
Key takeaways
  • 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)).
Interview questions
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.