PrepStack · Markdown HTML

KMP / prefix-function matching

String matching, hashing, and palindrome · HTML

Formal shape

pi[i] is the length of the longest proper prefix of pattern[0..i] that is also a suffix; j tracks the reusable prefix while scanning.

Recognition signals

False friends

SignalWhy it is different
Many patternsShared structure across patterns calls for a trie or multi-pattern automaton.
Approximate matchingAllowed edits or errors require DP or another distance method.

Core invariant

Before processing the next text character, j is the maximum prefix length equal to a suffix of the processed text.

State, transition, and processing order

ItemDefinition
StateThe pattern prefix-function pi, current matched length j, and match starts.
TransitionOn mismatch follow pi[j-1]; on equality increment j; at j==m report and fall back to permit overlap.
Frontier / orderThe text pointer moves only right; the pattern frontier retreats along border links without rereading text.

Python skeleton

def kmp_find_all(text, pat):
    if not pat: return list(range(len(text)+1))
    pi = [0] * len(pat)
    j = 0
    for i in range(1, len(pat)):
        while j and pat[i] != pat[j]: j = pi[j-1]
        if pat[i] == pat[j]: j += 1
        pi[i] = j
    ans, j = [], 0
    for i, ch in enumerate(text):
        while j and ch != pat[j]: j = pi[j-1]
        if ch == pat[j]: j += 1
        if j == len(pat):
            ans.append(i-len(pat)+1)
            j = pi[j-1]
    return ans

Correctness sketch

  1. pi records the longest reusable border of each pattern prefix.
  2. After mismatch, every longer candidate is disproved, so pi[j-1] skips no match.
  3. j==m exactly when the full pattern is a suffix ending at the current text position.
  4. The text never retreats and total movement of j is linear.

Complexity

TimeSpaceParameters
O(n+m)O(m) plus outputtext length n and pattern length m

Edge cases

Error patterns

PatternWhy it fails / fix
Resetting to zero on mismatchThis discards a reusable border.
Falling back only onceThe next candidate may still mismatch, so use while.
No fallback after a full matchThis can index past the pattern and misses overlaps.

Selection and exclusion rules

RelationTemplateBoundary
stream compositionParsing / token state machineMatching is one stage of token parsing
matching alternativeRolling hash / Rabin-KarpSubstring fingerprints and multiple lengths matter
contrastSubsequence dynamic programmingThe pattern must be contiguous rather than skippable.
multi-pattern extensionTrie prefix searchPatterns share prefixes

Original micro-example

PartDetail
ResultMatches start at 0 and 2.
ScenarioText ababab and pattern abab.
WalkthroughAfter the first match, j falls to the border ab of length 2; two more characters complete the overlapping match.

Recall prompts

My notes