Algorithms

Substring search and the KMP algorithm

Five symbols match and the sixth differs. Do we need to start checking from the beginning of the pattern again? Compare naive search with Knuth–Morris–Pratt and see which comparisons it can skip.

In the text, each step compares at most one pair per algorithm. Match positions start at 1.

KMP prefix table

Preparation comparisons 0
ABABAC——————

Naive search

Text comparisons 0
TextABABABACPatternABABAC

Ready to search.

Match positions —

KMP

Text comparisons 0
TextABABABACPatternABABAC

Ready to search.

Match positions —

KMP total with preparation 0

Video walkthrough

What KMP remembers about the pattern

A prefix is the beginning of a string, and a suffix is its end. For each initial segment of the pattern, the table stores the length of the longest fragment that is both a prefix and a suffix of that segment. The whole segment is excluded.

For ABABA, that fragment is ABA, of length 3. The table for ABABAC is 0, 0, 1, 2, 3, 0. While building the table, a mismatch sends us to a shorter candidate from an entry already computed.

A closer look at one comparison

Search for ABABAC in ABABABAC. The first five symbols spell ABABA in both. At position six, the text has B and the pattern has C. Naive search moves to the next starting position and compares again from the first symbol of the pattern.

KMP already knows that the end of the matched ABABA is also the start of the pattern, ABA. Shift the pattern two positions, keep those three matched symbols, and compare the sixth text symbol again, now with the fourth pattern symbol. The match begins at position three.

After each comparison, KMP keeps the length of the pattern prefix already matched at the end of the text it has read. On a mismatch, the table gives the next possible length. After a full match, another lookup keeps any overlap that could start the next occurrence.

How to read the counters

One comparison is one equality check between two symbols, including mismatches. During preparation, KMP compares symbols within the pattern. Then both algorithms check at most one pair in the text per playback step. Revisiting a step shows its previous state.

In the first example, naive search makes 13 comparisons in the text and KMP makes 9. KMP spends another 7 on preparation, for 16 in total. On a short text, preparation can cost more than the search saves. The same table can be reused for the same pattern in other texts.

For text length n and pattern length m, naive search takes O(nm) time in the worst case. KMP builds the table in O(m) and scans the text in O(n). Given arrays of symbols, working memory is O(1) for naive search and O(m) for KMP, excluding the result. The code below first copies the strings into arrays using O(n + m) space. The player also stores playback history.

JavaScript implementation

Like the demo, the code finds all occurrences, preserves spaces, and distinguishes case. A symbol is one Unicode code point. Positions start at 1. If the pattern is longer than the text, both searches return an empty result immediately.

Show executable code
function compareSubstringSearch(text, pattern) {
    const source = Array.from(text);
    const needle = Array.from(pattern);
    const ordinary = { positions: [], comparisons: 0 };
    const kmp = { positions: [], comparisons: 0, preparation: 0 };
    if (needle.length === 0) throw new RangeError("Empty pattern");
    if (needle.length > source.length) return { ordinary, kmp };

    for (let start = 0; start + needle.length <= source.length; start++) {
        for (let j = 0; j < needle.length; j++) {
            ordinary.comparisons++;
            if (source[start + j] !== needle[j]) break;
            if (j === needle.length - 1) ordinary.positions.push(start + 1);
        }
    }

    const prefix = [0];
    for (let i = 1, size = 0; i < needle.length;) {
        kmp.preparation++;
        if (needle[i] === needle[size]) prefix[i++] = ++size;
        else if (size > 0) size = prefix[size - 1];
        else prefix[i++] = 0;
    }

    for (let i = 0, j = 0; i < source.length;) {
        kmp.comparisons++;
        if (source[i] === needle[j]) {
            i++;
            j++;
            if (j === needle.length) {
                kmp.positions.push(i - j + 1);
                j = prefix[j - 1];
            }
        } else if (j > 0) {
            j = prefix[j - 1];
        } else {
            i++;
        }
    }
    return { ordinary, kmp };
}

Further reading

Knuth, Morris and Pratt — Fast Pattern Matching in Strings

Binary search in a sorted array