Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.

Examples:

Input:  txt[] = "THIS IS A TEST TEXT"
        pat[] = "TEST"
Output: Pattern found at index 10

Input:  txt[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern found at index 0
        Pattern found at index 9
        Pattern found at index 12

Python programming for Searching for Patterns Set 2 KMP Algorithm

Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.

[ad type=”banner”]

We have discussed Naive pattern searching algorithm in the previous post. The worst case complexity of Naive algorithm is O(m(n-m+1)). Time complexity of KMP algorithm is O(n) in worst case.

KMP (Knuth Morris Pratt) Pattern Searching
The Naive pattern searching algorithm doesn’t work well in cases where we see many matching characters followed by a mismatching character. Following are some examples.

txt[] = “AAAAAAAAAAAAAAAAAB”
pat[] = “AAAAB”

txt[] = “ABABABCABABABCABABABC”
pat[] = “ABABAC” (not a worst case, but a bad case for Naive)
The KMP matching algorithm uses degenerating property (pattern having same sub-patterns appearing more than once in the pattern) of the pattern and improves the worst case complexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch (after some matches), we already know some of the characters in the text of next window. We take advantage of this information to avoid matching the characters that we know will anyway match. Let us consider below example to understand this.

Matching Overview
txt = “AAAAABAAABA”
pat = “AAAA”

We compare first window of txt with pat
txt = “AAAAABAAABA”
pat = “AAAA” [Initial position] We find a match. This is same as Naive String Matching.

In the next step, we compare next window of txt with pat.
txt = “AAAAABAAABA”
pat = “AAAA” [Pattern shifted one position] This is where KMP does optimization over Naive. In this
second window, we only compare fourth A of pattern
with fourth character of current window of text to decide
whether current window matches or not. Since we know
first three characters will anyway match, we skipped
matching first three characters.

[ad type=”banner”]

Need of Preprocessing?
An important question arises from above explanation,
how to know how many characters to be skipped. To know
this, we pre-process pattern and prepare an integer array
lps[] that tells us count of characters to be skipped.
Preprocessing Overview:

KMP algorithm does preproceses pat[] and constructs an auxiliary lps[] of size m (same as size of pattern) which is used to skip characters while matching.
name lps indicates longest proper prefix which is also suffix.. A proper prefix is prefix with whole string not allowed. For example, prefixes of “ABC” are “”, “A”, “AB” and “ABC”. Proper prefixes are “”, “A” and “AB”. Suffixes of the string are “”, “C”, “BC” and “ABC”.
For each sub-pattern pat[0..i] where i = 0 to m-1, lps[i] stores length of the maximum matching proper prefix which is also a suffix of the sub-pattern pat[0..i].
lps[i] = the longest proper prefix of pat[0..i] which is also a suffix of pat[0..i].
Note : lps[i] could also be defined as longest prefix which is also proper suffix. We need to use proper at one place to make sure that the whole substring is not considered.

[ad type=”banner”]

Examples of lps[] construction:
For the pattern “AAAA”,
lps[] is [0, 1, 2, 3]

For the pattern “ABCDE”,
lps[] is [0, 0, 0, 0, 0]

For the pattern “AABAACAABAA”,
lps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]

For the pattern “AAACAAAAAC”,
lps[] is [0, 1, 2, 0, 1, 2, 3, 3, 3, 4]

For the pattern “AAABAAA”,
lps[] is [0, 1, 2, 0, 1, 2, 3] [ad type=”banner”] Searching Algorithm:
Unlike Naive algorithm, where we slide the pattern by one and compare all characters at each shift, we use a value from lps[] to decide the next characters to be matched. The idea is to not match character that we know will anyway match.

How to use lps[] to decide next positions (or to know number of characters to be skipped)?

We start comparison of pat[j] with j = 0 with characters of current window of text.
We keep matching characters txt[i] and pat[j] and keep incrementing i and j while pat[j] and txt[i] keep matching.
When we see a mismatch
We know that characters pat[0..j-1] match with txt[i-j+1…i-1] (Note that j starts with 0 and increment it only when there is a match).
We also know (from above definition) that lps[j-1] is count of characters of pat[0…j-1] that are both proper prefix and suffix.
From above two points, we can conclude that we do not need to match these lps[j-1] characters with txt[i-j…i-1] because we know that these characters will anyway match. Let us consider above example to understand this.
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
lps[] = {0, 1, 2, 3}

i = 0, j = 0
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j[ match, do i++, j++

i = 1, j = 1
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j[ match, do i++, j++

i = 2, j = 2
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
pat[i] and pat[j[ match, do i++, j++

i = 3, j = 3
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j[ match, do i++, j++

i = 4, j = 4
Since j == M, print pattern found and resset j,
j = lps[j-1] = lps[3] = 3

Here unlike Naive algorithm, we do not match first three
characters of this window. Value of lps[j-1] (in above
step) gave us index of next character to match.
i = 4, j = 3
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j[ match, do i++, j++

i = 5, j = 4
Since j == M, print pattern found and reset j,
j = lps[j-1] = lps[3] = 3

Again unlike Naive algorithm, we do not match first three
characters of this window. Value of lps[j-1] (in above
step) gave us index of next character to match.
i = 5, j = 3
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j] do NOT match and j > 0, change only j
j = lps[j-1] = lps[2] = 2

i = 5, j = 2
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j] do NOT match and j > 0, change only j
j = lps[j-1] = lps[1] = 1

i = 5, j = 1
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j] do NOT match and j > 0, change only j
j = lps[j-1] = lps[0] = 0

i = 5, j = 0
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j] do NOT match and j is 0, we do i++.

i = 6, j = 0
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j] match, do i++ and j++

i = 7, j = 1
txt[] = “AAAAABAAABA”
pat[] = “AAAA”
txt[i] and pat[j] match, do i++ and j++

[pastacode lang=”python” manual=”%23%20Python%20program%20for%20KMP%20Algorithm%0Adef%20KMPSearch(pat%2C%20txt)%3A%0A%20%20%20%20M%20%3D%20len(pat)%0A%20%20%20%20N%20%3D%20len(txt)%0A%20%0A%20%20%20%20%23%20create%20lps%5B%5D%20that%20will%20hold%20the%20longest%20prefix%20suffix%20%0A%20%20%20%20%23%20values%20for%20pattern%0A%20%20%20%20lps%20%3D%20%5B0%5D*M%0A%20%20%20%20j%20%3D%200%20%23%20index%20for%20pat%5B%5D%0A%20%0A%20%20%20%20%23%20Preprocess%20the%20pattern%20(calculate%20lps%5B%5D%20array)%0A%20%20%20%20computeLPSArray(pat%2C%20M%2C%20lps)%0A%20%0A%20%20%20%20i%20%3D%200%20%23%20index%20for%20txt%5B%5D%0A%20%20%20%20while%20i%20%3C%20N%3A%0A%20%20%20%20%20%20%20%20if%20pat%5Bj%5D%20%3D%3D%20txt%5Bi%5D%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%2B%3D%201%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%2B%3D%201%0A%20%0A%20%20%20%20%20%20%20%20if%20j%20%3D%3D%20M%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%20%22Found%20pattern%20at%20index%20%22%20%2B%20str(i-j)%0A%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20lps%5Bj-1%5D%0A%20%0A%20%20%20%20%20%20%20%20%23%20mismatch%20after%20j%20matches%0A%20%20%20%20%20%20%20%20elif%20i%20%3C%20N%20and%20pat%5Bj%5D%20!%3D%20txt%5Bi%5D%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20Do%20not%20match%20lps%5B0..lps%5Bj-1%5D%5D%20characters%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20they%20will%20match%20anyway%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20j%20!%3D%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20j%20%3D%20lps%5Bj-1%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20i%20%2B%3D%201%0A%20%0Adef%20computeLPSArray(pat%2C%20M%2C%20lps)%3A%0A%20%20%20%20len%20%3D%200%20%23%20length%20of%20the%20previous%20longest%20prefix%20suffix%0A%20%0A%20%20%20%20lps%5B0%5D%20%23%20lps%5B0%5D%20is%20always%200%0A%20%20%20%20i%20%3D%201%0A%20%0A%20%20%20%20%23%20the%20loop%20calculates%20lps%5Bi%5D%20for%20i%20%3D%201%20to%20M-1%0A%20%20%20%20while%20i%20%3C%20M%3A%0A%20%20%20%20%20%20%20%20if%20pat%5Bi%5D%3D%3Dpat%5Blen%5D%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20len%20%2B%3D%201%0A%20%20%20%20%20%20%20%20%20%20%20%20lps%5Bi%5D%20%3D%20len%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20%2B%3D%201%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20This%20is%20tricky.%20Consider%20the%20example.%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20AAACAAAA%20and%20i%20%3D%207.%20The%20idea%20is%20similar%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20to%20search%20step.%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20len%20!%3D%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20len%20%3D%20lps%5Blen-1%5D%0A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Also%2C%20note%20that%20we%20do%20not%20increment%20i%20here%0A%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20lps%5Bi%5D%20%3D%200%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20i%20%2B%3D%201%0A%20%0Atxt%20%3D%20%22ABABDABACDABABCABAB%22%0Apat%20%3D%20%22ABABCABAB%22%0AKMPSearch(pat%2C%20txt)%0A%20%0A%23%20This%20code%20is%20contributed%20by%20Bhavya%20Jain%0A” message=”Python” highlight=”” provider=”manual”/]

Output:
Found pattern at index 10
Preprocessing Algorithm:
In the preprocessing part, we calculate values in lps[]. To do that, we keep track of the length of the longest prefix suffix value (we use len variable for this purpose) for the previous index. We initialize lps[0] and len as 0. If pat[len] and pat[i] match, we increment len by 1 and assign the incremented value to lps[i]. If pat[i] and pat[len] do not match and len is not 0, we update len to lps[len-1]. See computeLPSArray () in the below code for details.

Illustration of preprocessing (or construction of lps[])

pat[] = “AAACAAAA”

len = 0, i = 0.
lps[0] is always 0, we move
to i = 1

len = 0, i = 1.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 1, lps[1] = 1, i = 2

len = 1, i = 2.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 2, lps[2] = 2, i = 3

len = 2, i = 3.
Since pat[len] and pat[i] do not match, and len > 0,
set len = lps[len-1] = lps[1] = 1

len = 1, i = 3.
Since pat[len] and pat[i] do not match and len > 0,
len = lps[len-1] = lps[0] = 0

len = 0, i = 3.
Since pat[len] and pat[i] do not match and len = 0,
Set lps[3] = 0 and i = 4.

len = 0, i = 4.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 1, lps[4] = 1, i = 5

len = 1, i = 5.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 2, lps[5] = 2, i = 6

len = 2, i = 6.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 3, lps[6] = 3, i = 7

len = 3, i = 7.
Since pat[len] and pat[i] do not match and len > 0,
set len = lps[len-1] = lps[2] = 2

len = 2, i = 7.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 3, lps[7] = 3, i = 8

We stop here as we have constructed the whole lps[].

[ad type=”banner”]