18. Knuth-Morris-Pratt Algorithm
Description
The Knuth-Morris-Pratt (KMP) algorithm is an efficient substring search algorithm that uses preprocessing of the pattern (search string) to speed up the search process. The algorithm was developed by Donald Knuth, Vaughan Pratt, and James H. Morris in 1977 and is an example of an algorithm with linear time complexity, making it significantly faster in practice than a simple brute-force approach.
Instead of checking whether every character in the string matches the pattern characters, the KMP algorithm uses information about previous mismatches to "skip" parts of the string that have already been checked and clearly cannot lead to a match. This significantly speeds up the search.
How the KMP Algorithm Works
- Pattern Preprocessing:
- First, the algorithm constructs an auxiliary array called the "prefix function". This array allows calculating how many characters of the pattern can be skipped when a mismatch occurs.
- The prefix function for a string is an array where each element
p[i]represents the length of the longest proper prefix of the substring ending at positionithat is also a suffix of this substring.
- For example, for the string
"ABAB", the prefix function looks like:[0, 0, 1, 2].
- Substring Search in String:
- Once the prefix function is built, the algorithm begins searching for occurrences of the pattern in the string. At each mismatch, the algorithm uses the prefix function to shift the pattern, avoiding re-checking characters that have already been checked.
- The runtime complexity of the algorithm is O(n + m), where
nis the length of the text string andmis the length of the pattern. Thus, substring search becomes linear in time, which is significantly faster on large strings compared to the naive method (which has a complexity of O(n ยท m)).
Algorithm Steps
- Convert pattern to prefix function:
- For each character of the pattern, a prefix function is constructed. It stores information about how much of a portion of the pattern matches its beginning.
- Substring search:
- The search process consists of sequentially checking characters of the text string, taking into account matches already found in the pattern. If a mismatch occurs, the algorithm shifts the pattern to the appropriate position using the prefix function.
Python Implementation
def compute_prefix_function(pattern):
m = len(pattern)
prefix_function = [0] * m
k = 0
for i in range(1, m):
while k > 0 and pattern[k] != pattern[i]:
k = prefix_function[k - 1]
if pattern[k] == pattern[i]:
k += 1
prefix_function[i] = k
return prefix_function
def kmp_search(text, pattern):
n = len(text)
m = len(pattern)
prefix_function = compute_prefix_function(pattern)
result = []
k = 0
for i in range(n):
while k > 0 and pattern[k] != text[i]:
k = prefix_function[k - 1]
if pattern[k] == text[i]:
k += 1
if k == m:
result.append(i - m + 1)
k = prefix_function[k - 1]
return result
Code Explanation
compute_prefix_function: This function builds the prefix function array for the pattern. It iterates over the characters of the pattern and fills theprefix_functionarray, which stores the length of the longest proper prefix that is also a suffix for each position in the pattern.
kmp_search: The main search function. It iterates through the text string, using the prefix function to efficiently shift the pattern upon mismatch. When the pattern matches a section of the text string completely, the starting index of the match is appended to the result list.
Example Walkthrough
If we have: text = "ababcababcabc" pattern = "abc"
The KMP algorithm will first construct the prefix function for the pattern "abc", which looks like: prefix_function = [0, 0, 0]
After that, the algorithm searches for occurrences of the pattern in the string. The matching starting indices found will be: Substrings 'abc' found at indices: [2, 6, 10]
Applications of the KMP Algorithm
- String Searching: KMP is an efficient solution for finding substrings in text and is used in various text-processing tasks, such as searching text files, text analysis, editing, and data processing.
- Text Processing Algorithms: The algorithm is used for efficient text search and analysis in applications like text editors, search engines, and document processors.
- Bioinformatics: In genome sequencing tasks where pattern occurrences must be found rapidly in long DNA sequences.
Advantages
- Linear Complexity: The KMP algorithm runs in O(n + m) time, where
nis the length of the string andmis the length of the pattern. This makes it much faster than naive "brute-force" algorithms.
- Efficiency on Large Strings: KMP is especially effective when working with long text strings and performing repeated searches for the same pattern.
Conclusion
The Knuth-Morris-Pratt algorithm is a powerful and efficient tool for substring search. It utilizes the concept of a prefix function to optimize searching and remains one of the classic algorithms for string processing.
All rights remain with the original author (Archiveskk). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me