M06 · Strings

String Matching: Naive Search and Knuth–Morris–Pratt

The naive search forgets everything after a mismatch. KMP precomputes, for every prefix of the pattern, its longest border, and uses it to slide the pattern without rereading the text. This lesson builds the prefix table, proves the O(n + m) bound, and compares both with the built-in search in C#, Java, Python and C++.

~50 minIntermediateC# · Python · Java · C++
Curriculum: M06 Strings · 3 of 3 lessons available

You will be able to

  • Trace the naive search and construct an input that makes it do (n − m + 1) · m comparisons.
  • Define a border and compute the prefix function (lps table) of a pattern by hand.
  • Explain how KMP uses lps[j − 1] after a mismatch, and why the text index never moves back.
  • Argue that KMP does O(n + m) comparisons with an amortised counting argument.
  • Choose between a hand-written search and the language built-in, and know what each compares.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

The problem

Given a text of length n and a non-empty pattern of length m, report every index s where text[s .. s + m) equals the pattern. Occurrences may overlap: "abab" occurs at 0, 2 and 7 in "abababcabab". All four listings return the full list; an empty pattern is rejected, because "every position matches" is a convention, not an answer.

Lay the pattern on the text at every alignment s = 0 … n − m and compare left to right until a mismatch or the end of the pattern.

for s in 0 .. n - m:
    j = 0
    while j < m and text[s + j] == pattern[j]:
        j = j + 1
    if j == m: report s

On ordinary text most alignments fail on the first or second character, so it is fast in practice. Its worst case is (n − m + 1) · m comparisons: a run of a's with the pattern "aaaab". Every alignment matches four characters and then fails. The lab's Naive: worst case preset needs 16 alignments × 5 comparisons = 80. The waste is clear in the trace: after matching "aaaa" at s, the search moves to s + 1 and compares the same text characters again, although it already knows what they are.

Borders and the prefix function

A border of a string is a proper prefix that is also a suffix. "abab" has the border "ab"; "aaaa" has "aaa", "aa" and "a"; "abc" has none (the empty border, length 0).

The prefix function stores, for every prefix of the pattern, the length of its longest border:

lps[q] = length of the longest proper prefix of pattern[0..q] that is also a suffix of it
q 0 1 2 3 4 5 6
pattern[q] a a b a a a b
lps[q] 0 1 0 1 2 2 3

Why it matters: suppose j characters of the pattern matched and the next one fails. The text just read ends with pattern[0..j). The next alignment that could still succeed is the one where a prefix of the pattern lines up with a suffix of what was matched, and the longest such overlap is exactly the border of pattern[0..j), of length lps[j − 1]. Shorter overlaps are tried later by falling back again.

Building the table

The table is built by matching the pattern against itself, with the same fallback idea:

lps[0] = 0; k = 0                    # k = length of the current border
for q in 1 .. m - 1:
    while k > 0 and pattern[q] != pattern[k]:
        k = lps[k - 1]               # try the next shorter border
    if pattern[q] == pattern[k]:
        k = k + 1                    # the border grows by one character
    lps[q] = k

In the KMP: rich table preset, at q = 5 the border "aa" (k = 2) cannot be extended because pattern[5] = 'a' differs from pattern[2] = 'b'. k falls back to lps[1] = 1, pattern[5] equals pattern[1], and lps[5] = 2. The lab draws the prefix being extended in a row behind the pattern, shifted so that the two characters being compared line up.

The KMP scan

j = 0                                # pattern characters matched
for i in 0 .. n - 1:
    while j > 0 and text[i] != pattern[j]:
        j = lps[j - 1]               # slide the pattern; i stays
    if text[i] == pattern[j]:
        j = j + 1
    if j == m:
        report i - m + 1
        j = lps[m - 1]               # keep the overlap: occurrences may overlap

Invariant: before comparing text[i], the j characters text[i − j .. i) equal pattern[0 .. j). A fallback replaces j with a smaller border length, which keeps the invariant because a border is both a prefix and a suffix. The unit tests check this invariant at every step of 200 random runs.

After a match, j = lps[m − 1] lets the next occurrence reuse the overlap. That is how KMP: overlapping finds "abab" at 0 and 2 without rereading.

Why KMP is O(n + m)

Count how j changes during the scan. Each iteration of the for loop increases j by at most 1, so j grows by at most n in total. Each fallback decreases j by at least 1, and j never goes below 0. So there are at most n fallbacks over the whole scan: at most 2n comparisons. The same argument on k bounds the table construction by 2m. Total O(n + m) time and O(m) extra space for the table.

On the naive worst-case input, KMP needs 42 comparisons (7 for the table, 35 for the scan) instead of 80, and the gap grows with m: for a pattern of a hundred a's followed by a b, the naive search does about 100 comparisons per alignment, KMP about 2 per text character.

Preprocessing Search Extra space Text index moves back?
Naive none O(n · m) worst, often near O(n) O(1) yes
KMP O(m) O(n) O(m) never (good for streams)

Because i only moves forward, KMP can search a stream it reads once, such as a network socket, without buffering the text.

What the built-ins do

Language Call Compares Notes
C# text.IndexOf(pattern, StringComparison.Ordinal) UTF-16 units Without Ordinal, the string overload uses culture-aware rules (CurrentCulture), which is slower and can match differently. Vectorised search internally.
Java text.indexOf(pattern, from) UTF-16 units No culture rules. Loop with from = found + 1 to get overlapping occurrences.
Python text.find(pattern, start) code points CPython uses a tuned two-way / Boyer–Moore–Horspool hybrid. re.finditer does not report overlapping matches unless you use a lookahead.
C++ text.find(pattern, pos); std::search with std::boyer_moore_searcher (C++17) bytes (char) find returns std::string::npos when there is no match.

Use the built-in in production; it is tested, vectorised and often sub-linear on average. Write KMP when you need its guarantees (worst-case linear, streaming, no backtracking) or its prefix table for other problems: the shortest period of a string is m − lps[m − 1], and searching for p in p + '#' + text turns the table itself into a matcher.

Language notes

The listings compare code units (C#, Java), code points (Python) and bytes (C++), and each test suite pins that down:

  • C# / Java: in "a😀b😀" the pattern "b😀" is found at index 3, because the emoji before it takes two UTF-16 units. Indices from IndexOf and indexOf count units too.
  • Python: the same search returns 2: str indexes code points.
  • C++: std::string_view holds bytes. Searching UTF-8 for a UTF-8 pattern is still correct, because UTF-8 is self-synchronising (a continuation byte can never match a lead byte), but the indices are byte offsets. The C++ naive loop is written s + m <= n rather than s <= n − m: with unsigned std::size_t, n − m wraps around to a huge number when m > n.
  • Normalisation: "café" with precomposed é and "cafe" + U+0301 do not match ordinally in any language. Normalise both strings first if they come from different sources.

Common mistakes

  • Resetting j to 0 after a mismatch instead of falling back with lps[j − 1]: that is the naive search with extra steps, and it misses overlapping occurrences.
  • Using lps[j] instead of lps[j − 1]. The border you need belongs to the matched part pattern[0..j), whose last index is j − 1.
  • Including the whole string as its own border. lps uses proper prefixes; otherwise lps[q] would always be q + 1 and the fallback would loop forever.
  • Moving i back. KMP never does; if your version does, the analysis no longer applies.
  • Forgetting j = lps[m − 1] after a match, which either reads past the pattern or loses overlapping matches.

Edge cases

  • Pattern longer than the text: no alignment fits; the naive loop body never runs, KMP scans and finds nothing.
  • Empty text: no matches.
  • Pattern of length 1: lps = [0]; KMP and naive do the same n comparisons.
  • Periodic patterns ("abcabc") have large lps values and produce overlapping matches.

Worked practice

1. Compute lps for "abcabd".

Answer

[0, 0, 0, 1, 2, 0]. "abca" has border "a", "abcab" has "ab", and "abcabd" has none because "d" cannot extend "ab" (pattern[2] = 'c') or the empty border (pattern[0] = 'a').

2. During a scan with pattern "abcabd", j = 5 ("abcab" matched) and the next text character is 'c'. What happens?

Answer

'c' differs from pattern[5] = 'd', so j = lps[4] = 2: "ab" stays matched. Then 'c' equals pattern[2], so j = 3. The text index did not move back.

3. What is the shortest period of "abababab"?

Answer

lps[7] = 6, so the period is 8 − 6 = 2: the string is "ab" repeated.

4. Give an input where the naive search does about n · m comparisons.

Answer

Text "aaaa…a" (n a's), pattern "aa…ab" (m − 1 a's then b). Every alignment matches m − 1 characters before failing on the b.

Summary

  • Naive search: simple, often fast, but O(n · m) in the worst case because it forgets what it matched.
  • lps[q] is the longest proper border of pattern[0..q]; it is built in O(m) by matching the pattern against itself.
  • KMP falls back to lps[j − 1] after a mismatch and never moves backwards in the text: O(n + m).
  • Built-ins are faster in practice; know whether they compare units, code points or bytes, and whether they are culture-aware.

Full implementation

Naive search, the prefix function and KMP in four languages, each checked against one shared fixture (overlaps, no match, pattern longer than text, empty text, periodic patterns) and 2,000 random texts over two- and three-letter alphabets compared with the language’s own substring search and a brute-force prefix function; each suite also checks what an index counts (UTF-16 units, code points or bytes).

namespace Bekadan.Dsa.Examples.Strings;
 
/// <summary>
/// Exact string matching: every start index of <c>pattern</c> in <c>text</c>,
/// overlapping occurrences included. Characters are compared as UTF-16 code
/// units with ordinal equality (no culture rules, no case folding).
/// </summary>
public static class StringMatching
{
    /// <summary>Tries every alignment. O(n · m) comparisons in the worst case, O(1) extra space.</summary>
    public static List<int> NaiveSearch(string text, string pattern)
    {
        ArgumentException.ThrowIfNullOrEmpty(pattern);
        var matches = new List<int>();
        int n = text.Length, m = pattern.Length;
        for (int s = 0; s <= n - m; s++)
        {
            int j = 0;
            while (j < m && text[s + j] == pattern[j])
                j++;
            if (j == m)
                matches.Add(s);
        }
        return matches;
    }
 
    /// <summary>
    /// The prefix function: lps[q] is the length of the longest proper prefix of
    /// pattern[0..q] that is also a suffix of it. O(m) time.
    /// </summary>
    public static int[] PrefixFunction(string pattern)
    {
        int m = pattern.Length;
        var lps = new int[m];  // lps[0] = 0
        int k = 0;             // length of the current border
        for (int q = 1; q < m; q++)
        {
            while (k > 0 && pattern[q] != pattern[k])
                k = lps[k - 1];
            if (pattern[q] == pattern[k])
                k++;
            lps[q] = k;
        }
        return lps;
    }
 
    /// <summary>Knuth–Morris–Pratt: O(n + m) time, O(m) extra space for the table.</summary>
    public static List<int> KmpSearch(string text, string pattern)
    {
        ArgumentException.ThrowIfNullOrEmpty(pattern);
        int[] lps = PrefixFunction(pattern);
        var matches = new List<int>();
        int j = 0;  // pattern characters matched so far
        for (int i = 0; i < text.Length; i++)
        {
            while (j > 0 && text[i] != pattern[j])
                j = lps[j - 1];  // keep the longest border that still matches
            if (text[i] == pattern[j])
                j++;
            if (j == pattern.Length)
            {
                matches.Add(i - j + 1);
                j = lps[j - 1];  // continue: occurrences may overlap
            }
        }
        return matches;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Strings/StringMatching.cs

"""Exact string matching: every start index of a pattern in a text.
 
Overlapping occurrences are included. Characters are compared as Python str
elements, which are Unicode code points (not bytes, not grapheme clusters).
"""
 
 
def naive_search(text: str, pattern: str) -> list[int]:
    """Try every alignment. O(n * m) comparisons in the worst case."""
    if not pattern:
        raise ValueError("the pattern must not be empty")
    matches: list[int] = []
    n, m = len(text), len(pattern)
    for s in range(n - m + 1):
        j = 0
        while j < m and text[s + j] == pattern[j]:
            j += 1
        if j == m:
            matches.append(s)
    return matches
 
 
def prefix_function(pattern: str) -> list[int]:
    """lps[q]: length of the longest proper prefix of pattern[:q + 1] that is also its suffix. O(m)."""
    m = len(pattern)
    lps = [0] * m  # lps[0] = 0
    k = 0  # length of the current border
    for q in range(1, m):
        while k > 0 and pattern[q] != pattern[k]:
            k = lps[k - 1]
        if pattern[q] == pattern[k]:
            k += 1
        lps[q] = k
    return lps
 
 
def kmp_search(text: str, pattern: str) -> list[int]:
    """Knuth-Morris-Pratt: O(n + m) time, O(m) extra space for the table."""
    if not pattern:
        raise ValueError("the pattern must not be empty")
    lps = prefix_function(pattern)
    matches: list[int] = []
    j = 0  # pattern characters matched so far
    for i in range(len(text)):
        while j > 0 and text[i] != pattern[j]:
            j = lps[j - 1]  # keep the longest border that still matches
        if text[i] == pattern[j]:
            j += 1
        if j == len(pattern):
            matches.append(i - j + 1)
            j = lps[j - 1]  # continue: occurrences may overlap
    return matches

Tested on CPython 3.14.0 · examples/python/dsa_examples/string_matching.py

package dev.bekadan.dsa.strings;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Exact string matching: every start index of {@code pattern} in {@code text},
 * overlapping occurrences included. Characters are compared as UTF-16 code
 * units ({@code char}), exactly like {@link String#indexOf(String)}.
 */
public final class StringMatching {
    private StringMatching() {
    }
 
    /** Tries every alignment. O(n * m) comparisons in the worst case, O(1) extra space. */
    public static List<Integer> naiveSearch(String text, String pattern) {
        requirePattern(pattern);
        List<Integer> matches = new ArrayList<>();
        int n = text.length(), m = pattern.length();
        for (int s = 0; s <= n - m; s++) {
            int j = 0;
            while (j < m && text.charAt(s + j) == pattern.charAt(j)) {
                j++;
            }
            if (j == m) {
                matches.add(s);
            }
        }
        return matches;
    }
 
    /**
     * The prefix function: lps[q] is the length of the longest proper prefix of
     * pattern[0..q] that is also a suffix of it. O(m) time.
     */
    public static int[] prefixFunction(String pattern) {
        int m = pattern.length();
        int[] lps = new int[m]; // lps[0] = 0
        int k = 0;              // length of the current border
        for (int q = 1; q < m; q++) {
            while (k > 0 && pattern.charAt(q) != pattern.charAt(k)) {
                k = lps[k - 1];
            }
            if (pattern.charAt(q) == pattern.charAt(k)) {
                k++;
            }
            lps[q] = k;
        }
        return lps;
    }
 
    /** Knuth-Morris-Pratt: O(n + m) time, O(m) extra space for the table. */
    public static List<Integer> kmpSearch(String text, String pattern) {
        requirePattern(pattern);
        int[] lps = prefixFunction(pattern);
        List<Integer> matches = new ArrayList<>();
        int j = 0; // pattern characters matched so far
        for (int i = 0; i < text.length(); i++) {
            while (j > 0 && text.charAt(i) != pattern.charAt(j)) {
                j = lps[j - 1]; // keep the longest border that still matches
            }
            if (text.charAt(i) == pattern.charAt(j)) {
                j++;
            }
            if (j == pattern.length()) {
                matches.add(i - j + 1);
                j = lps[j - 1]; // continue: occurrences may overlap
            }
        }
        return matches;
    }
 
    private static void requirePattern(String pattern) {
        if (pattern.isEmpty()) {
            throw new IllegalArgumentException("the pattern must not be empty");
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/strings/StringMatching.java

#pragma once
 
#include <cstddef>
#include <stdexcept>
#include <string_view>
#include <vector>
 
namespace bekadan::dsa {
 
// Exact string matching: every start index of pattern in text, overlapping
// occurrences included. std::string_view holds bytes (char), so this compares
// bytes: for UTF-8 text that is still correct, because a valid UTF-8 pattern
// can only match at a character boundary of valid UTF-8 text.
 
// Tries every alignment. O(n * m) comparisons in the worst case, O(1) extra space.
inline std::vector<std::size_t> naive_search(std::string_view text, std::string_view pattern) {
    if (pattern.empty()) throw std::invalid_argument("the pattern must not be empty");
    std::vector<std::size_t> matches;
    const std::size_t n = text.size(), m = pattern.size();
    for (std::size_t s = 0; s + m <= n; ++s) {  // s <= n - m would wrap around when m > n
        std::size_t j = 0;
        while (j < m && text[s + j] == pattern[j]) ++j;
        if (j == m) matches.push_back(s);
    }
    return matches;
}
 
// The prefix function: lps[q] is the length of the longest proper prefix of
// pattern[0..q] that is also a suffix of it. O(m) time.
inline std::vector<std::size_t> prefix_function(std::string_view pattern) {
    const std::size_t m = pattern.size();
    std::vector<std::size_t> lps(m, 0);  // lps[0] = 0
    std::size_t k = 0;                   // length of the current border
    for (std::size_t q = 1; q < m; ++q) {
        while (k > 0 && pattern[q] != pattern[k]) k = lps[k - 1];
        if (pattern[q] == pattern[k]) ++k;
        lps[q] = k;
    }
    return lps;
}
 
// Knuth-Morris-Pratt: O(n + m) time, O(m) extra space for the table.
inline std::vector<std::size_t> kmp_search(std::string_view text, std::string_view pattern) {
    if (pattern.empty()) throw std::invalid_argument("the pattern must not be empty");
    const std::vector<std::size_t> lps = prefix_function(pattern);
    std::vector<std::size_t> matches;
    std::size_t j = 0;  // pattern characters matched so far
    for (std::size_t i = 0; i < text.size(); ++i) {
        while (j > 0 && text[i] != pattern[j]) j = lps[j - 1];  // keep the longest border that still matches
        if (text[i] == pattern[j]) ++j;
        if (j == pattern.size()) {
            matches.push_back(i + 1 - j);
            j = lps[j - 1];  // continue: occurrences may overlap
        }
    }
    return matches;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/string_matching.hpp

References