| Start |
|---|
| Introduction To Knuth-Morris-Pratt (KMP) Algorithm Suppose that we have a text and a pattern. We need to determine if the pattern exists in the text or not. For example: This pattern does exist in the text. So our substring search should return 3, the index of the position from which this pattern starts. So how does our brute force substring search procedure work? What we usually do is: we start from the 0th index of the text and the 0th index of our *pattern and we compare Text[0] with Pattern[0]. Since they are not a match, we go to the next index of our text and we compare Text[1] with Pattern[0]. Since this is a match, we increment the index of our pattern and the index of the Text also. We compare Text[2] with Pattern[1]. They are also a match. Following the same procedure stated before, we now compare Text[3] with Pattern[2]. As they do not match, we start from the next position where we started finding the match. That is index 2 of the Text. We compare Text[2] with Pattern[0]. They don't match. Then incrementing index of the Text, we compare Text[3] with Pattern[0]. They match. Again Text[4] and Pattern[1] match, Text[5] and Pattern[2] match and Text[6] and Pattern[3] match. Since we've reached the end of our Pattern, we now return the index from which our match started, that is 3. If our pattern was: The Knuth-Morris-Pratt String Searching Algorithm (opens new window) or KMP Algorithm searches for occurrences of a "Pattern" within a main "Text" by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing re-examination of previously matched characters. The algorithm was conceived in 1970 by Donuld Knuth (opens new window) and Vaughan Pratt (opens new window) and independently by James H. Morris (opens new window). The trio published it jointly in 1977. Let's extend our example Text and Pattern for better understanding: At first, our Text and Pattern matches till index 2. Text[3] and Pattern[3] doesn't match. So our aim is to not go backwards in this Text, that is, in case of a mismatch, we don't want our matching to begin again from the position that we started matching with. To achieve that, we'll look for a suffix in our Pattern right before our mismatch occurred (substring abc), which is also a prefix of the substring of our Pattern. For our example, since all the characters are unique, there is no suffix, that is the prefix of our matched substring. So what that means is, our next comparison will start from index 0. Hold on for a bit, you'll understand why we did this. Next, we compare Text[3] with Pattern[0] and it doesn't match. After that, for Text from index 4 to index 9 and for Pattern from index 0 to index 5, we find a match. We find a mismatch in Text[10] and Pattern[6]. So we take the substring from Pattern right before the point where mismatch occurs (substring abcdabc), we check for a suffix, that is also a prefix of this substring. We can see here ab is both the suffix and prefix of this substring. What that means is, since we've matched until Text[10], the characters right before the mismatch is ab. What we can infer from it is that since ab is also a prefix of the substring we took, we don't have to check ab again and the next check can start from Text[10] and Pattern[2]. We didn't have to look back to the whole Text, we can start directly from where our mismatch occurred. Now we check Text[10] and Pattern[2], since it's a mismatch, and the substring before mismatch (abc) doesn't contain a suffix which is also a prefix, we check Text[10] and Pattern[0], they don't match. After that for Text from index 11 to index 17 and for Pattern from index 0 to index 6. We find a mismatch in Text[18] and Pattern[7]. So again we check the substring before mismatch (substring abcdabc) and find abc is both the suffix and the prefix. So since we matched till Pattern[7], abc must be before Text[18]. That means, we don't need to compare until Text[17] and our comparison will start from Text[18] and Pattern[3]. Thus we will find a match and we'll return 15 which is our starting index of the match. This is how our KMP Substring Search works using suffix and prefix information. Now, how do we efficiently compute if suffix is same as prefix and at what point to start the check if there is a mismatch of character between Text and Pattern. Let's take a look at an example: We'll generate an array containing the required information. Let's call the array S. The size of the array will be same as the length of the pattern. Since the first letter of the Pattern can't be the suffix of any prefix, we'll put S[0] = 0. We take i = 1 and j = 0 at first. At each step we compare Pattern[i] and Pattern[j] and increment i. If there is a match we put S[i] = j + 1 and increment j, if there is a mismatch, we check the previous value position of j (if available) and set j = S[j-1] (if j is not equal to 0), we keep doing this until S[j] doesn't match with S[i] or j doesn't become 0. For the later one, we put S[i] = 0. For our example: Pattern[j] and Pattern[i] don't match, so we increment i and since j is 0, we don't check the previous value and put Pattern[i] = 0. If we keep incrementing i, for i = 4, we'll get a match, so we put S[i] = S[4] = j + 1 = 0 + 1 = 1 and increment j and i. Our array will look like: Since Pattern[1] and Pattern[5] is a match, we put S[i] = S[5] = j + 1 = 1 + 1 = 2. If we continue, we'll find a mismatch for j = 3 and i = 7. Since j is not equal to 0, we put j = S[j-1]. And we'll compare the characters at i and j are same or not, since they are same, we'll put S[i] = j + 1. Our completed array will look like: This is our required array. Here a nonzero-value of S[i] means there is a S[i] length suffix same as the prefix in that substring (substring from 0 to i) and the next comparison will start from S[i] + 1 position of the Pattern. Our algorithm to generate the array would look like: The time complexity to build this array is Now let's do a substring search using the following example: |
| Introduction to Rabin-Karp Algorithm Rabin-Karp Algorithm (opens new window) is a string searching algorithm created by Richard M. Karp (opens new window) and Michael O. Rabin (opens new window) that uses hashing to find any one of a set of pattern strings in a text. A substring of a string is another string that occurs in. For example, ver is a substring of stackoverflow. Not to be confused with subsequence because cover is a subsequence of the same string. In other words, any subset of consecutive letters in a string is a substring of the given string. In Rabin-Karp algorithm, we'll generate a hash of our pattern that we are looking for & check if the rolling hash of our text matches the pattern or not. If it doesn't match, we can guarantee that the pattern doesn't exist in the text. However, if it does match, the pattern can be present in the text. Let's look at an example: Let's say we have a text: yeminsajid and we want to find out if the pattern nsa exists in the text. To calculate the hash and rolling hash, we'll need to use a prime number. This can be any prime number. Let's take prime = 11 for this example. We'll determine hash value using this formula: We'll denote: The hash value of nsa will be: Now we find the rolling-hash of our text. If the rolling hash matches with the hash value of our pattern, we'll check if the strings match or not. Since our pattern has 3 letters, we'll take 1st 3 letters yem from our text and calculate hash value. We get: This value doesn't match with our pattern's hash value. So the string doesn't exists here. Now we need to consider the next step. To calculate the hash value of our next string emi. We can calculate this using our formula. But that would be rather trivial and cost us more. Instead, we use another technique.
The new hash value is not equal to our patterns hash value. Moving on, for n we get: It doesn't match. After that, for s, we get: It doesn't match. Next, for a, we get: It's a match! Now we compare our pattern with the current string. Since both the strings match, the substring exists in this string. And we return the starting position of our substring. The pseudo-code will be: Hash Calculation: Hash Recalculation: String Match: Rabin-Karp: If the algorithm doesn't find any match, it simply returns -1. This algorithm is used in detecting plagiarism. Given source material, the algorithm can rapidly search through a paper for instances of sentences from the source material, ignoring details such as case and punctuation. Because of the abundance of the sought strings, single-string searching algorithms are impractical here. Again, Knuth-Morris-Pratt algorithm or Boyer-Moore String Search algorithm is faster single pattern string searching algorithm, than Rabin-Karp. However, it is an algorithm of choice for multiple pattern search. If we want to find any of the large number, say k, fixed length patterns in a text, we can create a simple variant of the Rabin-Karp algorithm. For text of length n and p patterns of combined length m, its average and best case running time is O(n+m) in space O(p), but its worst-case time is O(nm). |
| KMP Algorithm in C Given a text txt and a pattern pat, the objective of this program will be to print all the occurance of pat in txt. Examples: Input: output: Input: output: C Language Implementation: Output: Reference: http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/ (opens new window) |
| Python Implementation of KMP algorithm. Haystack: The string in which given pattern needs to be searched. Time complexity: Search portion (strstr method) has the complexity O(n) where Note: Following implementation returns the start position of match in haystack (if there is a match) else returns -1, for edge cases like if needle/haystack is an empty string or needle is not found in haystack. |
Read Article
https://develop.horje.com/learn/1434/reference