Video in progress

When is the naive way of searching for a pattern in text slow? How do KMP and Rabin-Karp help?

Naive search is O(n·m) in the worst case, for example when you search for "aaaa…ab" inside "aaaa…a". KMP uses a prefix function to run in O(n+m) without moving backward. Rabin-Karp slides the window in O(1) with a rolling hash, which is handy for searching many patterns at once, but collisions must be verified.

📖 Answer

String.indexOf is close to the naive algorithm in practice (and very fast thanks to JIT intrinsics), and on ordinary text it's enough. The problem appears on pathological input, with a user-supplied pattern and a large text.

The KMP idea: on a mismatch, we know which part of the pattern has already matched. lps[i] is the longest proper prefix of pattern[0..i] that is also a suffix at the same time.

static 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 to a shorter prefix
        else lps[i++] = 0;
    }
    return lps;
}

static int indexOf(String text, String p) {
    if (p.isEmpty()) return 0;
    int[] lps = lps(p);
    for (int i = 0, j = 0; i < text.length(); ) {
        if (text.charAt(i) == p.charAt(j)) {
            i++; j++;
            if (j == p.length()) return i - j;
        } else if (j > 0) j = lps[j - 1];
        else i++;
    }
    return -1;
}

The text pointer i never moves backward, so it suits streaming input too.

Rabin-Karp: we update the window hash with h = (h - c_out·B^(m-1))·B + c_in mod M. If the hashes are equal, we actually compare the characters; otherwise a collision gives a wrong answer. Its strengths: searching many patterns (of the same length) in a single pass with a HashSet, plagiarism detection, matching blocks with a rolling checksum (rsync), and splitting files with content-defined chunking (dedup systems).

If the hash modulus and base are easy to learn in advance, an attacker can deliberately craft collisions. Choosing the base randomly protects against that.

For a very large number of patterns (say a dictionary of banned words), there is Aho-Corasick: a combination of a Trie and KMP that finds all of them in one pass.

One more senior note: a user-supplied regex, Pattern.compile(userInput), can be exponential because of backtracking (ReDoS). If all you need is a simple substring search, don't use a regex.