Developing the KMP Logic
I'm now zeroing in on the core of the KMP algorithm. My focus is squarely on crafting a clear explanation of its logic, ensuring it's easily digestible. I'm building a robust and comprehensive picture of the process, moving from high-level understanding to actionable steps.
Defining the LPS Array
I'm deep into the definition and purpose of the LPS array. It's becoming clear that this array is the linchpin of KMP's efficiency. I'm focusing on the "why" - how the LPS array allows us to skip unnecessary comparisons. Currently, I'm working through examples to build an intuitive understanding of this critical piece of the algorithm.
Elaborating Search Implementation
I've been solidifying the search implementation details. My focus now is on translating the high-level descriptions into precise steps. I am constructing the code's control flow, particularly when handling pattern mismatches and successful matches. I'm focusing on the edge cases and how to manage the pattern pointer without unnecessary backtracking through the text.
Structuring the Output Plan
I'm now fully immersed in organizing the output. I'm focusing on the logical flow, starting with the introduction and culminating in the complexity analysis and dry run. I want to build in a strong visual example to explain the LPS array. I'm prioritizing clarity for the user, ensuring a smooth progression from high-level concepts to concrete implementation details. I also am striving to ensure my example is simple.
Codifying the KMP Logic
I'm now concretely codifying the KMP algorithm logic, including the lps array computation and the search function. I'm focusing on ensuring accuracy and readability in the Python code itself. This involves carefully translating the conceptual understanding into syntactically correct and efficient code. I am thinking about how the different parts work together to achieve the efficient search.
Refining the Explanation
I'm now laser-focused on refining the explanation, targeting the trickier aspects. I'm double-checking the clarity of proper prefixes and suffixes, making sure the fallback logic, especially len = lps[len-1], is crystal clear. I'm also ensuring the code robustly handles edge cases, like empty strings and pattern lengths exceeding text lengths, as that's always good practice.
The Knuth-Morris-Pratt (KMP) algorithm is an efficient string-matching algorithm that searches for occurrences of a "pattern" within a "text".
Unlike the naive approach, which shifts the pattern by one character upon a mismatch, KMP uses a pre-computed table (called the LPS array) to skip characters that we know typically match, achieving a time complexity of O(N + M) where N is the text length and M is the pattern length.
Here is the comprehensive guide to the algorithm, logic, and implementation.
1. The Core Concept: The LPS Array
The heart of KMP is the LPS (Longest Prefix Suffix) array. For each index in the pattern, we calculate the length of the longest proper prefix that is also a suffix.
Why? If a mismatch occurs at index j in the pattern, we know that the characters before j matched the text. The LPS array tells us how much of the pattern matches itself, so we can slide the pattern to align the prefix with the matched suffix instead of starting over.
Example: Pattern = A B A B C
A: LPS = 0
A B: LPS = 0
A B A: LPS = 1 (Prefix 'A' matches Suffix 'A')
A B A B: LPS = 2 (Prefix 'AB' matches Suffix 'AB')
A B A B C: LPS = 0
2. The Algorithm Steps
Phase 1: Preprocessing (Building LPS)
- Create an array
lps[] of size M (length of pattern).
- Initialize
len = 0 (length of previous longest prefix) and i = 1.
- Loop while
i < M:
- If
pat[i] == pat[len]:
- Increment
len.
lps[i] = len.
- Increment
i.
- If
pat[i] != pat[len]:
- If
len > 0, set len = lps[len - 1] (do not increment i, we check against the previous prefix).
- If
len == 0, set lps[i] = 0 and increment i.
Phase 2: Searching
- Initialize
i = 0 (pointer for text) and j = 0 (pointer for pattern).
- Loop while
i < N (length of text):
- If
pat[j] == txt[i]:
- If
j == M (Pattern Found):
- Record match found at index
i - j.
- Update
j = lps[j - 1] to continue searching for more occurrences.
- If
pat[j] != txt[i] (Mismatch):
- If
j > 0, set j = lps[j - 1] (skip comparisons using LPS).
- If
j == 0, increment i (character matches nothing, move to next text char).
3. Implementation (Python)
def compute_LPS_array(pattern, M, lps):
"""
Precomputes the Longest Prefix Suffix (LPS) array.
"""
length = 0 # length of the previous longest prefix suffix
i = 1
lps[0] = 0 # lps[0] is always 0
while i < M:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
# If mismatch, fall back to the previous character's LPS length
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
def KMP_search(text, pattern):
"""
Performs the KMP search algorithm.
"""
M = len(pattern)
N = len(text)
if M == 0: return [] # Edge case handling
# Create lps[] that will hold the longest prefix suffix values for pattern
lps = [0] * M
compute_LPS_array(pattern, M, lps)
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:
# Pattern found
found_indices.append(i - j)
# Reset j to find the 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
# --- Driver Code ---
text = "ABABDABACDABABCABAB"
pattern = "ABABCABAB"
matches = KMP_search(text, pattern)
if matches:
print(f"Pattern found at indices: {matches}")
else:
print("Pattern not found")
4. Dry Run Example
Text: AAAAABAA
Pattern: AAAA
LPS computation for AAAA: [0, 1, 2, 3]
Search Steps:
i=0, j=0: Match (A vs A) -> i=1, j=1
i=1, j=1: Match (A vs A) -> i=2, j=2
i=2, j=2: Match (A vs A) -> i=3, j=3
i=3, j=3: Match (A vs A) -> i=4, j=4
j=4 (Match found at index 0). Update j = lps[3] (which is 3).
i=4, j=3: Match (B vs A) -> Mismatch!
- Handle Mismatch:
j != 0, so j = lps[2] (which is 2).
i=4, j=2: Match (B vs A) -> Mismatch!
- Handle Mismatch:
j != 0, so j = lps[1] (which is 1).
i=4, j=1: Match (B vs A) -> Mismatch!
- Handle Mismatch:
j != 0, so j = lps[0] (which is 0).
i=4, j=0: Match (B vs A) -> Mismatch!
- Handle Mismatch:
j == 0, so increment i -> i=5.
- Continue...
5. Complexity Analysis
- Time Complexity: O(N + M)
- O(M) to compute the LPS array.
- O(N) to search the text. Even though the variable
j effectively moves backward in the pattern upon mismatch, the variable i (text index) never moves backward.
- Space Complexity: O(M)
- We require an array of size
M to store the LPS values.