Algorithm · Strings · naive O(n·m) worst; KMP O(n + m)

String matching: naive and KMP

Find every occurrence of a pattern in a text: the naive scan tries each alignment in O(nm); Knuth–Morris–Pratt never moves back in the text, O(n + m).

The full derivation, edge cases and exercises are in the lesson String matching: naive search and Knuth–Morris–Pratt. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

The naive method compares the pattern at every starting position. On inputs like “aaaa…b” it re-reads the same text characters again and again.

KMP precomputes, for every prefix of the pattern, the longest proper prefix that is also a suffix. After a mismatch it slides the pattern so that much stays matched, so the text index only moves forward.

Steps

  1. Build the prefix function lps for the pattern in O(m).
  2. Scan the text with j = characters matched so far.
  3. On a match advance j; on a full match record it and set j = lps[j − 1].
  4. On a mismatch with j > 0 set j = lps[j − 1] and compare again; with j = 0 move on.

Invariants

What holds at every step; the correctness argument rests on these.

  • pattern[0 … j) equals the j text characters just before the current position.
  • The text index never decreases.

Complexity

String matching: naive and KMP complexity
CaseTimeExtra space
NaiveO(n · m) worstO(1)
KMPO(n + m)O(m)

When to use it

Use it when

  • Searching long texts or streams for a fixed pattern with guaranteed linear time.

Avoid it when

  • Short strings: the built-in search (IndexOf, str.find, String.indexOf, std::string::find) is simpler and well optimized.

Step through it

The interactive lab for string matching: naive and kmp: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Data structures it uses

Problems, patterns and exercises

References