📖 Scenario: You are building a simple text search tool that finds all positions where a small pattern appears inside a larger text. This is useful in searching documents, DNA sequences, or logs quickly.
🎯 Goal: Implement the Knuth-Morris-Pratt (KMP) algorithm to efficiently find all starting indexes of a pattern inside a given text.
📋 What You'll Learn
Create a list called lps to store longest prefix suffix values for the pattern
Create a function compute_lps(pattern) to fill the lps list
Create a function kmp_search(text, pattern) that uses lps to find all pattern matches in the text
Print the list of starting indexes where the pattern is found in the text
💡 Why This Matters
🌍 Real World
Text search is used in search engines, DNA sequence analysis, plagiarism detection, and log file analysis.
💼 Career
Understanding KMP algorithm helps in roles involving software development, data processing, and algorithm optimization.
Progress0 / 4 steps
1
Create the text and pattern variables
Create a variable called text and set it to the string 'ABABDABACDABABCABAB'. Create a variable called pattern and set it to the string 'ABABCABAB'.
DSA Python
Hint
Use simple string assignment for both text and pattern.
2
Create the LPS array and the compute_lps function
Create a list called lps with length equal to len(pattern) filled with zeros. Define a function called compute_lps(pattern) that fills the lps list with longest prefix suffix values for the given pattern. Use variables length and i inside the function to track prefix length and current index.
DSA Python
Hint
The lps list stores the length of the longest proper prefix which is also a suffix for each prefix of the pattern.
3
Create the kmp_search function to find pattern matches
Define a function called kmp_search(text, pattern) that uses the lps list to find all starting indexes where pattern appears in text. Use variables i for text index and j for pattern index. Return a list called result containing all matching start indexes.
DSA Python
Hint
Use two pointers to scan the text and pattern. When characters match, move both pointers. When mismatch occurs, use lps to avoid rechecking characters.
4
Print the list of pattern match starting indexes
Call the function kmp_search(text, pattern) and print the returned list of starting indexes where the pattern is found in the text.
DSA Python
Hint
The pattern appears starting at index 10 in the text. Printing the result list shows [10].
Practice
(1/5)
1. What is the main purpose of the KMP (Knuth-Morris-Pratt) pattern matching algorithm?
easy
A. To calculate the factorial of a number recursively
B. To sort an array of numbers in ascending order
C. To reverse a string in linear time
D. To find occurrences of a pattern string within a text efficiently
Solution
Step 1: Understand the goal of KMP algorithm
KMP is designed to search for a pattern inside a larger text efficiently without rechecking characters unnecessarily.
Step 2: Compare with other options
Sorting, reversing strings, and factorial calculations are unrelated to pattern searching.
Final Answer:
To find occurrences of a pattern string within a text efficiently -> Option D
Quick Check:
KMP = Pattern search [OK]
Hint: KMP is about fast pattern search in text [OK]
Common Mistakes:
Confusing KMP with sorting algorithms
Thinking KMP reverses strings
Assuming KMP calculates mathematical functions
2. Which of the following is the correct way to initialize the prefix table (lps array) in KMP algorithm in Python?
easy
A. lps = [0] * len(pattern)
B. lps = []
C. lps = [1] * len(pattern)
D. lps = None
Solution
Step 1: Understand the prefix table initialization
The prefix table (lps array) stores lengths of longest proper prefix which is also suffix for each prefix of the pattern. It must be initialized with zeros for all positions.
Step 2: Check each option
lps = [0] * len(pattern) correctly initializes lps with zeros for the entire pattern length. lps = [] is empty list, which is incomplete. lps = [1] * len(pattern) initializes with ones, which is incorrect. lps = None sets None, which is invalid.
Final Answer:
lps = [0] * len(pattern) -> Option A
Quick Check:
Prefix table starts with zeros [OK]
Hint: Prefix table starts with zeros for all pattern chars [OK]
Common Mistakes:
Initializing lps with ones instead of zeros
Leaving lps empty
Assigning None to lps
3. What will be the output of the following Python code snippet using KMP algorithm?
def compute_lps(pattern):
lps = [0] * len(pattern)
length = 0
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
pattern = "ABABC"
lps = compute_lps(pattern)
print(lps)