Data Structures and Algorithms • C# examples
Knuth-Morris-Pratt (KMP) Pattern Matching
Search for a pattern in text without rescanning characters already known to match.
Concept
KMP preprocesses the pattern into a prefix table describing the longest proper prefix that is also a suffix. On mismatch, the table chooses the next viable pattern position while preserving prior comparisons. This gives linear matching time even for repetitive inputs.
How to approach it
Build the prefix function carefully, then use it to update the matched-prefix length after each text character.
Complexity
O(n + m) time and O(m) extra space for text length n and pattern length m.
C# example
if (pattern.Length == 0) return 0;
while (matched > 0 && pattern[matched] != text[i])
matched = prefix[matched - 1];
if (pattern[matched] == text[i]) matched++;
if (matched == pattern.Length) ReportMatch(i - pattern.Length + 1);
Expected result or behavior
The prefix table skips impossible alignments while retaining reusable matched characters.
Practice exercise
Trace the prefix values for a pattern with repeated prefixes, such as “ababaca”.
Key takeaway: Preprocessing turns repeated mismatch work into a linear scan.