0
0
DSA Pythonprogramming~10 mins

KMP Pattern Matching Algorithm in DSA Python - Execution Trace

Choose your learning style9 modes available
Concept Flow - KMP Pattern Matching Algorithm
Build LPS array for pattern
Start matching pattern with text
Compare characters
End
First, build the LPS array for the pattern. Then, scan the text comparing characters. On mismatch, use LPS to shift pattern index without moving text index. Repeat until pattern found or text ends.
Execution Sample
DSA Python
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
This code builds the LPS array for the pattern, which helps skip unnecessary comparisons during matching.
Execution Table
StepOperationPattern Index (j)Text Index (i)LPS ArrayActionVisual State
1Build LPS array start0-[0, 0, 0, 0, 0]Initialize lps and pointersPattern: A B C A B LPS: 0 0 0 0 0
2Compare pattern[1] and pattern[0]1-[0, 0, 0, 0, 0]No match, length=0, lps[1]=0, i=2LPS: 0 0 0 0 0
3Compare pattern[2] and pattern[0]2-[0, 0, 0, 0, 0]No match, length=0, lps[2]=0, i=3LPS: 0 0 0 0 0
4Compare pattern[3] and pattern[0]3-[0, 0, 0, 1, 0]Match, length=1, lps[3]=1, i=4LPS: 0 0 0 1 0
5Compare pattern[4] and pattern[1]4-[0, 0, 0, 1, 2]Match, length=2, lps[4]=2, i=5LPS: 0 0 0 1 2
6Start matching text00[0, 0, 0, 1, 2]Compare text[0] and pattern[0]Text: A B C A B C A B Pattern: A B C A B
7Match text[0] and pattern[0]11[0, 0, 0, 1, 2]Characters match, advance bothMatch so far: A
8Match text[1] and pattern[1]22[0, 0, 0, 1, 2]Characters match, advance bothMatch so far: A B
9Match text[2] and pattern[2]33[0, 0, 0, 1, 2]Characters match, advance bothMatch so far: A B C
10Match text[3] and pattern[3]44[0, 0, 0, 1, 2]Characters match, advance bothMatch so far: A B C A
11Match text[4] and pattern[4]55[0, 0, 0, 1, 2]Full pattern matched at index 0Pattern found at text index 0
12Continue matching26[0, 0, 0, 1, 2]Mismatch at text[6], pattern[5]; shift pattern using LPSShift pattern index to 2
13Match text[6] and pattern[2]36[0, 0, 0, 1, 2]Characters match, advance bothMatch so far: C
14Match text[7] and pattern[3]47[0, 0, 0, 1, 2]Characters match, advance bothMatch so far: C A
15Match text[8] and pattern[4]58[0, 0, 0, 1, 2]Full pattern matched at index 3Pattern found at text index 3
16End-9[0, 0, 0, 1, 2]Text fully scannedMatching complete
💡 Text fully scanned or pattern found at all possible positions
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 11After Step 12After Step 15Final
lps[0,0,0,0,0][0,0,0,1,0][0,0,0,1,2][0,0,0,1,2][0,0,0,1,2][0,0,0,1,2][0,0,0,1,2]
pattern_index (j)034525-
text_index (i)---5689
match_found_positions[][][][0][0][0,3][0,3]
Key Moments - 3 Insights
Why do we use the LPS array to shift the pattern index instead of moving the text index on mismatch?
Because the LPS array tells us the longest prefix which is also suffix, so we can avoid re-checking characters in the text that we know already matched. This is shown in step 12 where pattern_index shifts using LPS but text_index stays the same.
Why does the pattern index sometimes move backward during LPS computation?
When characters don't match during LPS building, we use the previous LPS value to try a smaller prefix. This avoids starting over from zero. See steps 2 and 3 where length stays 0 and lps[i] is set to 0.
How do we know when the full pattern is matched in the text?
When the pattern index reaches the length of the pattern (step 11 and 15), it means all characters matched consecutively. We then record the match position.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 5, what is the LPS array value at index 4?
A0
B1
C2
D3
💡 Hint
Check the 'LPS Array' column at step 5 in the execution_table
At which step does the first full pattern match occur in the text?
AStep 11
BStep 10
CStep 12
DStep 15
💡 Hint
Look for 'Full pattern matched' in the 'Action' column of execution_table
If the pattern index did not shift using LPS at step 12, what would happen to the text index?
AIt would stay the same
BIt would move forward by one
CIt would move backward
DIt would reset to zero
💡 Hint
Step 12 shows pattern index shifting without moving text index; without LPS, text index moves forward on mismatch
Concept Snapshot
KMP Pattern Matching Algorithm:
- Build LPS (Longest Prefix Suffix) array for pattern
- Use LPS to skip unnecessary comparisons
- Compare text and pattern characters
- On mismatch, shift pattern index using LPS, keep text index
- On full match, record position
- Efficiently finds all pattern occurrences in text
Full Transcript
The KMP Pattern Matching Algorithm first builds an LPS array for the pattern. This array helps to know how far to shift the pattern when a mismatch happens during matching. We then scan the text and pattern characters together. When characters match, we advance both indexes. When a mismatch occurs, instead of moving the text index forward, we use the LPS array to shift the pattern index to avoid re-checking characters. This process continues until the entire text is scanned or all pattern matches are found. The execution table shows step-by-step how the LPS array is built and how the matching proceeds, including pattern shifts and matches found.