The Knuth-Morris-Pratt (KMP) algorithm is a string matching algorithm that finds occurrences of a pattern within a text in linear time. The key insight is the "longest prefix suffix" (LPS) array (also called the "failure function" or "partial match table").
Let me explain the concept first:
- The LPS array stores, for each position in the pattern, the length of the longest proper prefix that is also a suffix up to that position.
- When a mismatch occurs during pattern matching, instead of moving the text pointer back (backtracking), we use the LPS array to determine how much of the pattern we can skip.
Let me implement this with detailed comments:
def compute_lps(pattern):
"""
Compute the Longest Prefix Suffix (LPS) array for the pattern.
The LPS array stores, at each position i, the length of the longest proper
prefix of pattern[0:i+1] that is also a suffix of pattern[0:i+1].
For example:
- pattern = "ABAB"
- LPS = [0, 0, 1, 2]
- LPS[0] = 0: "A" has no proper prefix that is also a suffix
- LPS[1] = 0: "AB" has no proper prefix that is also a suffix
- LPS[2] = 1: "ABA" - "A" is both prefix and suffix
- LPS[3] = 2: "ABAB" - "AB" is both prefix and suffix
This optimization allows the KMP algorithm to skip ahead without backtracking.
"""
m = len(pattern)
lps = [0] * m
length = 0 # length of previous longest prefix suffix
i = 1
while i < m:
if pattern[i] == pattern[length]:
# Extend the current prefix-suffix match
length += 1
lps[i] = length
i += 1
else:
# When characters don't match, fall back to the previous LPS value
# rather than starting from scratch—this is what makes KMP efficient
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
def kmp_search(text, pattern):
"""
Perform KMP pattern matching on the text.
"""
Time Complexity: O(n + m) where n = len(text), m = len(pattern)
Space Complexity: O(m) for the LPS array
Returns: List of indices where pattern is found in text
"""
if not pattern or not text:
return []
n = len(text)
m = len(pattern)
# Build the LPS array first
lps = compute_lps(pattern)
matches = []
i = 0 # text pointer
j = 0 # pattern pointer
while i < n:
if text[i] == pattern[j]:
i += 1
j += 1
if j == m:
# Found a match at position i - j
matches.append(i - j)
# Continue searching by using the LPS array to skip unnecessary comparisons
j = lps[j - 1]
elif i < n and text[i] != pattern[j]:
# When characters don't match, the LPS array tells us how many characters we can safely skip since they're already known to match at the pattern's beginning. For instance, with pattern "ABABC", if we've matched "ABAB" but fail on the next character, lps[3] = 2 means the suffix "AB" matches the prefix "AB", so we jump j to 2 instead of restarting from 0.
if j != 0:
j = lps[j - 1]
else:
i += 1
return matches
The algorithm efficiently finds all pattern occurrences by leveraging the LPS array to avoid redundant comparisons. When a mismatch occurs after partial matches, it uses the precomputed overlap information to skip ahead rather than restarting the pattern matching from the beginning. < n and text[i] != pattern[j]:
if j != 0:
j = lps[j - 1]
print(f" ✗ Mismatch! Skipping {j - lps[j-1]} pattern characters using LPS")
else:
i += 1
print(f" ✗ No match at pattern start, advancing text pointer")
print()
return matches
Test cases
if name == "main":
print("=" * 70)
print("TEST 1: Simple pattern")
print("=" * 70)
result = kmp_search_verbose("
When there's a mismatch and we haven't reached the pattern start, I use the LPS table to jump ahead in the pattern without backtracking through the text. If we're already at the pattern beginning, I just move forward in the text instead.
The test cases then run through several scenarios: a straightforward pattern match, repeated characters, patterns with overlapping prefix-suffix structures, and a case with no matches. After that, I compare the KMP approach against a naive search implementation to show the efficiency gains.
The key insight is that KMP never backtracks the text pointer—it only moves forward. This becomes increasingly valuable when dealing with large texts and intricate patterns where naive substring matching would repeatedly restart comparisons.
Knuth-Morris-Pratt (KMP) String Matching Algorithm
def compute_lps(pattern):
"""
Compute the Longest Prefix Suffix (LPS) array.
The LPS array stores at each position i the length of the longest proper
prefix of pattern[0:i+1] that is also a suffix of pattern[0:i+1].
This array is the KEY to KMP's efficiency. It tells us: "When a mismatch
occurs, how much of the pattern can we reuse without backtracking in the
text string?"
Example: pattern = "ABABCABAB"
Index: 0 1 2 3 4 5 6 7 8
Pattern: A B A B C A B A B
LPS: 0 0 1 2 0 1 2 3 4
LPS[8]=4 means "ABAB" is both a prefix and suffix of "ABABCABAB"
So if we mismatch at position 9, we know the last 4 chars already matched!
Time: O(m), Space: O(m) where m = len(pattern)
"""
m = len(pattern)
lps = [0] * m # lps[i] = length of longest proper prefix that is suffix
length = 0 # length of previous longest prefix suffix
i = 1
while i < m:
if pattern[i] == pattern[length]:
# Characters match: extend the length
length += 1
lps[i] = length
i += 1
else:
# Mismatch: this is where LPS helps ITSELF
# Instead of linear search, jump back using previous LPS value
if length != 0:
# Don't reset to 0; jump to lps[length-1]
# This is the nested property that makes LPS efficient
length = lps[length - 1]
else:
# No prefix-suffix match possible
lps[i] = 0
i += 1
return lps
def kmp_search(text, pattern):
"""
KMP Pattern Matching Algorithm.
WHY NO BACKTRACKING IN TEXT?
============================
When mismatch occurs at text[i], the LPS array tells us exactly how many
characters we can "skip" in the pattern because they already matched.
The text pointer i NEVER moves backward - we only move j (pattern pointer).
Example: Searching for "ABABC" in "ABABDABABC"
Position 0-3: "ABAD" vs "ABAB" ✓✓✓✗ (mismatch at position 3)
Naive approach: Reset pattern pointer to 0, re-examine text position 1
KMP approach: Use LPS[2]=1. Since "AB" at end is also at start,
jump pattern pointer to 1 directly!
Position 4: We continue from "D" without wasting time!
Time: O(n + m), Space: O(m)
n = len(text), m = len(pattern)
"""
if not pattern or not text or len(pattern) > len(text):
return []
n = len(text)
m = len(pattern)
# Step 1: Build the failure function (LPS array)
lps = compute_lps(pattern)
matches = []
i = 0 # pointer in text (NEVER BACKTRACKS)
j = 0 # pointer in pattern
while i < n:
# ===== MATCHING PHASE =====
if text[i] == pattern[j]:
# Characters match, advance both pointers
i += 1
j += 1
# ===== PATTERN FOUND =====
if j == m:
matches.append(i - j) # Found match at index i-j
# Continue searching for overlapping matches
# Use LPS to skip without text backtracking
j = lps[j - 1]
# ===== MISMATCH PHASE (THE MAGIC OF KMP) =====
elif i < n and text[i] != pattern[j]:
if j != 0:
# THIS IS WHERE KMP SHINES:
# Instead of moving text pointer back (backtracking),
# we move pattern pointer using LPS value
# What LPS[j-1] tells us:
# - We matched j characters: pattern[0:j]
# - LPS[j-1] = how many we can skip
# - Because lps[j-1] chars at START match the END
# Example: pattern "ABABCAB", we matched "ABABCA" (j=6)
# LPS[5]=2 means "AB" at end = "AB" at start
# So we jump j to 2, not 0! We don't re-examine those chars
j = lps[j - 1]
# NOTE: i does NOT move backward! This is the key efficiency
else:
# j == 0: we're at the start, mismatch means move text pointer
i += 1
return matches
# ============================================================================
# VISUALIZATION & EDUCATIONAL VERSION
# ============================================================================
def kmp_search_animated(text, pattern):
"""
Step-by-step visualization showing how LPS prevents backtracking.
"""
print(f"\n{'='*75}")
print(f"KMP SEARCH VISUALIZATION")
print(f"{'='*75}\n")
print(f"Text: {text}")
print(f"Pattern: {pattern}\n")
if not pattern or not text:
return []
n = len(text)
m = len(pattern)
# Build LPS array
lps = compute_lps(pattern)
print(f"LPS Array Computation:")
print(f"{'Index':<8} {'Pattern':<15} {'LPS':<6} {'Explanation'}")
print("-" * 70)
for idx in range(m):
substr = pattern[:idx + 1]
lps_val = lps[idx]
if lps_val > 0:
prefix = pattern[:lps_val]
suffix = substr[-lps_val:]
explanation = f"'{prefix}' (prefix) = '{suffix}' (suffix)"
else:
explanation = "No prefix-suffix match"
print(f"{idx:<8} {substr:<15} {lps_val:<6} {explanation}")
print(f"\n{'='*75}")
print(f"SEARCH PROCESS (Text pointer NEVER backtracks)")
print(f"{'='*75}\n")
matches = []
i = 0
j = 0
step = 0
while i < n:
step += 1
# Show current state
text_marked = list(text)
text_marked[i] = f"[{text[i]}]"
pattern_marked = list(pattern)
if j < m:
pattern_marked[j] = f"[{pattern[j]}]"
print(f"Step {step}:")
print(f" Text: {' '.join(text_marked)}")
print(f" Pattern: {' '.join(pattern_marked) if j > 0 else ' ' + ' '.join(['_'] * m)}")
print(f" Pointers: i={i}, j={j}")
if j < m and text[i] == pattern[j]:
print(f" ✓ MATCH: '{text[i]}' == '{pattern[j]}'")
i += 1
j += 1
if j == m:
print(f" 🎉 PATTERN FOUND at index {i - j}!")
matches.append(i - j)
j = lps[j - 1]
print(f" Continuing search with j = LPS[{j}] = {lps[j]}")
elif i < n and text[i] != pattern[j]:
if j != 0:
print(f" ✗ MISMATCH: '{text[i]}' != '{pattern[j]}'")
print(f" → Using LPS[{j-1}] = {lps[j-1]} to skip ahead in pattern")
print(f" → Text pointer i={i} STAYS SAME (no backtracking!)")
print(f" → Pattern pointer j jumps from {j} to {lps[j-1]}")
j = lps[j - 1]
else:
print(f" ✗ MISMATCH at pattern start")
print(f" → Moving text pointer forward")
i += 1
print()
return matches
# ============================================================================
# TEST CASES
# ============================================================================
if __name__ == "__main__":
# Test 1: Simple pattern
print("\n" + "▶" * 40)
print("TEST 1: Simple Pattern with Overlap")
print("▶" * 40)
text1 = "ABABDABACDABABCABAB"
pattern1 = "ABABCABAB"
matches1 = kmp_search_animated(text1, pattern1)
print(f"Matches found at indices: {matches1}")
# Test 2: Highly repetitive pattern
print("\n" + "▶" * 40)
print("TEST 2: Repetitive Pattern (shows LPS power)")
print("▶" * 40)
text2 = "AAAAAAAAB"
pattern2 = "AAAB"
matches2 = kmp_search_animated(text2, pattern2)
print(f"Matches found at indices: {matches2}")
# Test 3: None found
print("\n" + "▶" * 40)
print("TEST 3: Pattern Not Found")
print("▶" * 40)
text3 = "ABCDEFGH"
pattern3 = "XYZ"
matches3 = kmp_search_animated(text3, pattern3)
print(f"Matches found at indices: {matches3}")
# Performance comparison
print("\n" + "="*75)
print("COMPLEXITY ANALYSIS")
print("="*75)
print("""
Naive Algorithm:
- Time: O(n*m) in worst case
- Must backtrack in text when mismatch occurs
- Example: searching "AAAB" in "AAAAAAAAAB"
Text pointer might need to re-examine previous character
KMP Algorithm:
- Preprocessing: O(m) to build LPS array
- Search: O(n) - text pointer NEVER backtracks
- Total: O(n + m)
WHY TEXT POINTER NEVER BACKTRACKS:
1. When mismatch occurs at position i in text
2. LPS tells us how much of pattern overlaps with itself
3. We reuse that overlap information
4. So we never need to re-examine text[i]
5. Text pointer only moves forward or stays same
""")
Key Insights
| Concept | Explanation |
|---|
| LPS Array | Encodes the pattern's self-overlap structure |
| No Backtracking | When mismatch occurs, use LPS to skip pattern positions, not text positions |
| Efficiency | Text pointer moves forward only - never backward |
| Time Complexity | O(n + m) instead of O(n*m) for naive approach |
The critical advantage: The text pointer i never decrements. It only moves forward or stays the same, while the pattern pointer j jumps backward using the LPS array. This prevents redundant comparisons of the same text characters.