The user wants a program that implements the KMP (Knuth-Morris-Pratt) string matching algorithm.
Understand the Goal: The goal is to provide code (likely in Python, C++, or Java, but Python is usually the most accessible for explaining algorithms) that searches for occurrences of a "pattern" string within a "text" string using the KMP algorithm.
Identify Key Components of KMP:
The Problem: Find indices where pattern exists in text.
The Naive Approach: O(N×M). Checks every position.
The KMP Advantage: O(N+M). Avoids re-checking characters that we know match.
Core Mechanism: The "Partial Match Table" (also called "Prefix Table" or "LPS" - Longest Prefix Suffix).
The Search Loop: Iterates through the text using information from the LPS table to skip ahead efficiently.
Determine the Programming Language: Python is excellent for readability. I will provide a Python implementation, but I might briefly mention how it works generally. I'll stick to Python for the primary code block because it looks like pseudocode, making the logic easy to follow.
Step-by-Step Implementation Plan:
Step 1: Build the LPS (Longest Prefix Suffix) Array.
Input: The pattern string.
Output: An array where lps[i] is the length of the longest proper prefix of pattern[0...i] that is also a suffix of pattern[0...i].
Logic:
Use two pointers: length (tracking prefix length) and i (current index in pattern).
If pattern[i] == pattern[length]: Match found, increment length, store length in lps[i], increment i.
If mismatch:
If length != 0: Backtrack length to lps[length - 1] (don't increment i).
If length == 0: No prefix matches here, set lps[i] = 0, increment i.
Step 2: The Search Algorithm.
Input: Text, Pattern, LPS array.
Logic:
Use two pointers: i (for text) and j (for pattern).
Loop while i < length of text.
If text[i] == pattern[j]: Increment both.
If j reaches length of pattern: Match Found! Record index (i - j). Reset j using lps[j - 1] to find overlapping matches.
If mismatch:
If j != 0: Reset j to lps[j - 1].
If j == 0: Increment i.
Drafting the Code (Mental or Scratchpad):
python
def compute_lps_array(pattern):
length = 0
lps = [0] * len(pattern)
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
def kmp_search(text, pattern):
if not pattern: return []
lps = compute_lps_array(pattern)
i = 0 # text index
j = 0 # pattern index
results = []
while i < len(text):
if text[i] == pattern[j]:
i += 1
j += 1
if j == len(pattern):
results.append(i - j)
j = lps[j - 1] # Continue searching
elif i < len(text) and text[i] != pattern[j]:
if j != 0:
j = lps[j - 1]
else:
i += 1
return results
Refining the Explanation:
I need to explain why we need the LPS array. It's the "memory" of the pattern.
I should provide an example usage case to show it works.
I should add comments in the code for clarity.
Language Selection: The prompt doesn't specify a language. Python is safest, but adding C++ or Java is a nice bonus for students or interview prep. I will stick to Python for the main detailed implementation because it maps best to the algorithmic logic, but I will make the code clean and standard.
Final Code Structure:
Function compute_lps_array.
Function kmp_search.
Main block to demonstrate usage.
Reviewing Edge Cases:
Pattern is empty? The code should handle it (usually return 0 matches or error, I'll handle gracefully).
Multiple matches? The j = lps[j-1] line handles overlapping matches (e.g., text="AAAA", pattern="AA"). Wait, standard KMP finds "AA" at 0 and 1. The code logic j = lps[j-1] after a match handles this correctly.
Constructing the Final Output:
Start with a brief explanation of the algorithm.
Provide the Python code.
Explain the compute_lps part.
Explain the search part.
Give an example output.
This thought process moves from understanding requirements to selecting tools, drafting logic, handling edge cases, and formatting the final response. The resulting Python code is robust and readable.
Here is a clean, well-commented implementation of the Knuth-Morris-Pratt (KMP) algorithm in Python.
The KMP algorithm optimizes string matching by avoiding redundant comparisons. It consists of two main parts:
Building the LPS Array (Longest Prefix Suffix): Pre-processing the pattern to find repeating sub-patterns.
The Search: Using the LPS array to skip ahead in the text without missing any matches.
Python Implementation
python
def compute_lps_array(pattern):
"""
Computes the Longest Prefix Suffix (LPS) array.
lps[i] = the longest proper prefix of pattern[0...i]
that is also a suffix of pattern[0...i].
"""
length = 0 # Length of the previous longest prefix suffix
i = 1
lps = [0] * len(pattern)
# The loop calculates lps[i] for i = 1 to len(pattern)-1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
# This is tricky. Consider the example "AAACAAAA"
# and i = 7. The idea is similar to search step.
if length != 0:
length = lps[length - 1]
# Also, note that we do not increment i here
else:
lps[i] = 0
i += 1
return lps
def kmp_search(text, pattern):
"""
Searches for occurrences of 'pattern' within 'text' using KMP algorithm.
Returns a list of starting indices where the pattern is found.
"""
M = len(pattern)
N = len(text)
# Edge case: empty pattern matches everywhere (or nowhere depending on definition)
# Standard convention: empty pattern returns no matches or index 0.
# Here we return empty list for empty pattern for clarity.
if M == 0:
return []
# 1. Create the LPS array
lps = compute_lps_array(pattern)
i = 0 # index for text[]
j = 0 # index for pattern[]
found_indices = []
while i < N:
if pattern[j] == text[i]:
i += 1
j += 1
if j == M:
# A complete match is found
found_indices.append(i - j)
# Move j to continue searching for next occurrence
j = lps[j - 1]
# Mismatch after j matches
elif i < N and pattern[j] != text[i]:
# Do not match lps[0..lps[j-1]] characters,
# they will match anyway
if j != 0:
j = lps[j - 1]
else:
i += 1
return found_indices
# --- Example Usage ---
if __name__ == "__main__":
text_input = "ABABDABACDABABCABAB"
pattern_input = "ABABCABAB"
print(f"Text: {text_input}")
print(f"Pattern: {pattern_input}")
result = kmp_search(text_input, pattern_input)
if result:
print(f"Pattern found at indices: {result}")
else:
print("Pattern not found.")
# Visual verification for the example:
# Index 10: ABABCABAB fits starting at index 10 in the text.
How it works
Pre-processing (compute_lps_array):
Normally, if a mismatch occurs at index j of the pattern, we might have to start over from the beginning of the pattern.
The LPS array prevents this. It tells us: "If you fail at index j, you can safely jump back to index lps[j-1] because the characters before that index already match the text."
For the pattern "ABABCABAB", the LPS array is [0, 0, 1, 2, 0, 1, 2, 3, 4].
Searching (kmp_search):
We iterate through the text with index i and the pattern with index j.
Match: Increment both i and j.
Mismatch: Instead of resetting j to 0 and i back to where it started + 1 (like the Naive algorithm), we set j = lps[j-1]. This keeps i moving forward constantly, making the algorithm efficient.
Complexity
Time Complexity: O(N+M), where N is the text length and M is the pattern length.