The user wants a program that implements the KMP string matching algorithm.
1. Understand the Request:
- Goal: Write a program for KMP string matching.
- Algorithm: KMP (Knuth-Morris-Pratt).
- Language: Not specified. Python is usually the default for clarity, but C++ or Java are also common for algorithms. I will provide the solution in Python as it's highly readable, but I might add a C++ or Java version if I feel generous, or just stick to Python to be concise. Let's stick to Python for the primary explanation and code, as it's pseudo-code-like.
- Components of KMP:
- The
lps (Longest Prefix Suffix) array construction (also called the "failure function" or "pi array").
- The main search loop using the
lps array.
2. The Logic of KMP:
- Problem: Find occurrences of a
pattern inside a text.
- Naive approach: O(N*M). When a mismatch occurs, we shift the pattern by 1 and start over.
- KMP improvement: When a mismatch occurs, we don't need to start from the beginning of the pattern. We use knowledge from previous matches. This is stored in the
lps array.
- LPS Array:
lps[i] stores the length of the longest proper prefix of pattern[0...i] that is also a suffix of pattern[0...i].
- Example: Pattern "ABABC"
- i=0 ('A'): 0
- i=1 ('AB'): 0
- i=2 ('ABA'): 'A' is prefix and suffix -> 1
- i=3 ('ABAB'): 'AB' is prefix and suffix -> 2
- i=4 ('ABABC'): 0
3. Drafting the Code Structure (Python):
4. Refinement and Explanations:
- I should explain why this works briefly.
- I need to provide a driver code example so the user can run it.
- Time complexity analysis: O(N + M) where N is text length, M is pattern length. Space complexity: O(M) for the LPS array.
5. Writing the Code (Mental Check):
-
LPS Calculation:
- Pattern: "AABAABAAA"
- lps: [0, 1, 0, 1, 2, 3, 4, 5, 2]
- Let's trace the logic:
- i=1, char='A'. Match len(0)='A'. len=1. lps=[0,1]
- i=2, char='B'. Mismatch len(1)='A'. len=lps[0]=0. loop check again. match len(0)='A'? No. lps[2]=0.
- i=3, char='A'. Match len(0)='A'. len=1. lps=[0,1,0,1]
- Looks correct.
-
Search:
- Text: "ABABDABACDABABCABAB"
- Pattern: "ABABCABAB"
- Standard test case.
6. Language Choice:
I will write this in Python because it is the most accessible language for demonstrating algorithms. It removes the syntax noise of memory management or strict typing found in C++ or Java, though I could include those if requested. Since the prompt is general, Python is the safest bet for a clear explanation.
7. Structuring the Output:
- Brief explanation of the algorithm logic (LPS array).
- Python code implementation.
- Time/Space complexity analysis.
- Example usage output.
8. Self-Correction during drafting:
9. Final Code Assembly:
Construct the Python script with comments explaining each step.
(Self-Correction on formatting): The user asked for "A program". I will provide a complete script that can be copy-pasted and run.
Let's proceed with generating the response based on this plan.
Here is a complete implementation of the Knuth-Morris-Pratt (KMP) algorithm in Python.
The code is broken down into two parts:
- The LPS Array Construction: A helper function to preprocess the pattern. LPS stands for "Longest Prefix Suffix." This table tells the algorithm how many characters to skip after a mismatch.
- The KMP Search Algorithm: The main function that uses the LPS array to efficiently find the pattern within the text.
Python Implementation
def compute_lps_array(pattern):
"""
Computes the Longest Prefix Suffix (LPS) array for the pattern.
lps[i] = the longest proper prefix of pattern[0...i] that is also a suffix.
"""
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
if length != 0:
# Backtrack 'length' to the previous valid prefix position
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):
"""
The main KMP search function.
Returns a list of starting indices where the pattern is found in the text.
"""
m = len(pattern)
n = len(text)
# Edge case: Empty pattern matches everywhere (or nowhere depending on definition)
if m == 0:
return []
lps = compute_lps_array(pattern)
i = 0 # index for text
j = 0 # index for pattern
matches = []
while i < n:
if pattern[j] == text[i]:
i += 1
j += 1
if j == m:
# Found a match
matches.append(i - j)
# Move pattern using LPS to find next potential match
j = lps[j - 1]
elif i < n and pattern[j] != text[i]:
# Mismatch after j matches
if j != 0:
# Don't increment i, just move pattern using LPS
j = lps[j - 1]
else:
# If j is 0 (first char mismatch), just move to next text char
i += 1
return matches
# --- Example Usage ---
if __name__ == "__main__":
sample_text = "ABABDABACDABABCABAB"
sample_pattern = "ABABCABAB"
print(f"Text: {sample_text}")
print(f"Pattern: {sample_pattern}")
result_indices = kmp_search(sample_text, sample_pattern)
if result_indices:
print(f"Pattern found at indices: {result_indices}")
for index in result_indices:
print(f"Match at index {index}: {sample_text[index:index+len(sample_pattern)]}")
else:
print("Pattern not found.")
How it Works
-
Pre-processing (compute_lps_array):
- Standard pattern matching requires backing up in the text string when a mismatch occurs. KMP avoids this.
- Before searching, we analyze the pattern itself. For every position in the pattern, we calculate the length of the longest proper prefix that is also a suffix.
- Example: For pattern "ABAB", the prefix "AB" is also the suffix. If we match "ABA" and then fail on the next character, we know we can instantly jump back to the state representing "AB" rather than starting over.
-
Searching (kmp_search):
- We iterate through the
text with index i and pattern with index j.
- Match: If
text[i] == pattern[j], we advance both.
- Mismatch:
- If we haven't matched anything in the pattern yet (
j == 0), we just move to the next character in the text (i += 1).
- If we have matched some characters, we use the
lps array to figure out where to reset j (the pattern index) without moving i (the text index) backward.
- Complexity: The pre-processing takes O(M) time and the search takes O(N time, where is text length and is pattern length. The total time complexity is .