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

String matching: naive and KMP

Find every occurrence; KMP builds the prefix table, then scans without moving back.

The full explanation, derivation and practice are in the lesson String matching: naive search and Knuth–Morris–Pratt.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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