Open In App

Python Program for KMP Algorithm for Pattern Searching

Last Updated : 08 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

 
 

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. 
 

Python3




# Python program for KMP Algorithm
def KMPSearch(pat, txt):
    M = len(pat)
    N = len(txt)
 
    # create lps[] that will hold the longest prefix suffix
    # values for pattern
    lps = [0]*M
    j = 0 # index for pat[]
 
    # Preprocess the pattern (calculate lps[] array)
    computeLPSArray(pat, M, lps)
 
    i = 0 # index for txt[]
    while i < N:
        if pat[j] == txt[i]:
            i += 1
            j += 1
 
        if j == M:
            print ("Found pattern at index", str(i-j))
            j = lps[j-1]
 
        # mismatch after j matches
        elif i < N and pat[j] != txt[i]:
            # Do not match lps[0..lps[j-1]] characters,
            # they will match anyway
            if j != 0:
                j = lps[j-1]
            else:
                i += 1
 
def computeLPSArray(pat, M, lps):
    len = 0 # length of the previous longest prefix suffix
 
    lps[0] # lps[0] is always 0
    i = 1
 
    # the loop calculates lps[i] for i = 1 to M-1
    while i < M:
        if pat[i]== pat[len]:
            len += 1
            lps[i] = len
            i += 1
        else:
            # This is tricky. Consider the example.
            # AAACAAAA and i = 7. The idea is similar
            # to search step.
            if len != 0:
                len = lps[len-1]
 
                # Also, note that we do not increment i here
            else:
                lps[i] = 0
                i += 1
 
txt = "ABABDABACDABABCABAB"
pat = "ABABCABAB"
KMPSearch(pat, txt)
 
# This code is contributed by Bhavya Jain


Output: 

Found pattern at index 10

 

Time Complexity: O(m+n)

Space Complexity: O(m)

Please refer complete article on KMP Algorithm for Pattern Searching for more details!
 



Previous Article
Next Article

Similar Reads

Python Program for KMP Algorithm for Pattern Searching[duplicate]
Python Code # Python program for KMP Algorithm def KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i &lt; N: if pat[j] == txt[i]:
2 min read
Python Program for Rabin-Karp Algorithm for Pattern Searching
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 &gt; 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 inde
3 min read
Python Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14-&gt;21-&gt;11-&gt;30-&gt;10, then function should return false. If key to be searched is 1
4 min read
Python Program to print digit pattern
The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples: Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *'s that are equivalent to each digit in the integer. Here the first digit is 4 so print four *sin the fir
3 min read
Python 3 | Program to print double sided stair-case pattern
Below mentioned is the Python 3 program to print the double-sided staircase pattern. Examples: Input: 10Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note: This code only works for even values of n. Example1 The given Python code demonstrates a staircase pattern. It d
3 min read
Python Program to print hollow half diamond hash pattern
Give an integer N and the task is to print hollow half diamond pattern. Examples: Input : 6 Output : # # # # # # # # # # # # # # # # # # # # Input : 7 Output : # # # # # # # # # # # # # # # # # # # # # # # # Approach: The idea is to break the pattern into two parts: Upper part: For the upper half start the for loop with iterator (i) from 1 to n and
4 min read
Python program to print the Inverted heart pattern
Let us see how to print an inverted heart pattern in Python. Example: Input: 11 Output: * *** ***** ******* ********* *********** ************* *************** ***************** ******************* ********************* ********* ******** ******* ****** ***** **** Input: 15 Output: * *** ***** ******* ********* *********** ************* ***********
2 min read
Python Program to Print Alphabetic Triangle Pattern
In this article, we examine a recursive method for printing character patterns in Python. Nesting loops are used in the conventional iterative approach to regulating character spacing and printing. We have provided the answer using both methods. This method prints an alphabet pattern in the form of a pyramid. It uses nested loops to print the space
4 min read
Python Program to Print the Natural Numbers Summation Pattern
Given a natural number n, the task is to write a Python program to first find the sum of first n natural numbers and then print each step as a pattern. Input: 5 Output: 1 = 11 + 2 = 31 + 2 + 3 = 61 + 2 + 3 + 4 = 101 + 2 + 3 + 4 + 5 = 15 Input: 10 Output: 1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15 1 + 2 + 3 + 4 + 5 + 6 =
2 min read
Python program to display half diamond pattern of numbers with star border
Given a number n, the task is to write a Python program to print a half-diamond pattern of numbers with a star border. Examples: Input: n = 5 Output: * *1* *121* *12321* *1234321* *123454321* *1234321* *12321* *121* *1* * Input: n = 3 Output: * *1* *121* *12321* *121* *1* * Approach: Two for loops will be run in this program in order to print the n
2 min read