This is a great question about the KMP (Knuth-Morris-Pratt) algorithm. Let me build the LPS (Longest Proper Prefix that is also Suffix) array for the pattern "ABABAC" step by step.
Understanding LPS
The LPS array stores for each position i in the pattern, the length of the longest proper prefix of pattern[0...i] that is also a suffix of pattern[0...i].
A "proper" prefix/suffix means it's not equal to the whole string.
Building LPS for "ABABAC"
Pattern: A B A B A C
Index: 0 1 2 3 4 5
Let me build this step by step:
Position 0 (A):
- Proper prefixes of "A": none (empty string only, but that's not proper)
- LPS[0] = 0
Position 1 (AB):
- Proper prefixes: "A"
- Proper suffixes: "B"
- Do any match? No
- LPS[1] = 0
Position 2 (ABA):
- Proper prefixes: "", "A", "AB"
- Proper suffixes: "", "A", "BA"
- Matching: "A" matches
- LPS[2] = 1
Position 3 (ABAB):
- Proper prefixes: "", "A", "AB", "ABA"
- Proper suffixes: "", "B", "AB", "BAB"
- Matching: "AB" matches
- LPS[3] = 2
Position 4 (ABABA):
-
Proper prefixes: "", "A", "AB", "ABA", "ABAB"
-
Proper suffixes: "", "A", "BA", "ABA", "BABA"
-
Matching: "ABA" matches
-
LPS[4] = 3
At the final position, "ABABAC" has no matching proper prefix and suffix since the "C" breaks the pattern, giving us LPS[5] = 0. The complete LPS array is [0, 0, 1, 2, 3, 0].
The algorithm builds this array iteratively by comparing characters and using previously computed LPS values to efficiently backtrack when mismatches occur. Starting with LPS[0] = 0, we maintain a length variable tracking the current prefix-suffix match. When characters align, we increment the length and record it; when they don't, we use the LPS table itself to jump back to the longest matching position rather than restarting from zero.
For "ABABAC", this produces [0, 0, 1, 2, 3, 0] by matching progressively longer overlaps until the final 'C' breaks the pattern, forcing a reset to check against earlier positions in the pattern.
During actual text matching, when a mismatch occurs, the LPS array tells us exactly where to resume in the pattern without backtracking through the text. With text "ABABDABABABAC" and pattern "ABABAC", we advance through matching characters, but when we hit the 'D' at position 4, the LPS value guides us to the right restart point rather than abandoning all progress.
At the mismatch, we check LPS[3] = 2, which indicates the first 2 characters of the pattern already matched at the end of our current progress. We jump the pattern index to 2 and continue comparing from the same text position. When another mismatch occurs, we repeat this process using LPS[1] = 0, resetting to the pattern's beginning and moving forward through the text.
From position 5 onward, we match "ABAB" successfully until hitting a mismatch at position 10 where "B" doesn't equal "C". The LPS value tells us the first 3 characters align with what we've already matched, so we shift to pattern index 3. From there, the remaining characters "BC" match perfectly, completing the search at position 12.
The key advantage of KMP is that it eliminates text backtracking entirely. When a mismatch occurs, the LPS array reveals how much of the pattern's beginning overlaps with its end, allowing us to skip ahead without revisiting previous text positions. This overlap structure means we can shift the pattern forward by exactly (j - LPS[j-1]) positions, achieving O(m + n) time complexity instead of the naive O(m × n) approach.
KMP LPS Array Construction for "ABABAC"
Step-by-Step LPS Array Construction
For pattern ABABAC, I'll build the Longest Proper Prefix Suffix array, which stores for each position the length of the longest prefix that is also a suffix (excluding the whole string).
Manual Construction
Pattern: A B A B A C
Index: 0 1 2 3 4 5
Position 0: "A"
- No proper prefix/suffix
- LPS[0] = 0
Position 1: "AB"
- Prefixes: "A" | Suffixes: "B"
- No overlap
- LPS[1] = 0
Position 2: "ABA"
- Prefixes: "A", "AB" | Suffixes: "A", "BA"
- "A" matches! ✓
- LPS[2] = 1
Position 3: "ABAB"
- Prefixes: "A", "AB", "ABA" | Suffixes: "B", "AB", "BAB"
- "AB" matches! ✓
- LPS[3] = 2
Position 4: "ABABA"
- Prefixes: "A", "AB", "ABA", "ABAB" | Suffixes: "A", "BA", "ABA", "BABA"
- "ABA" matches! ✓
- LPS[4] = 3
Position 5: "ABABAC"
- Prefixes: "A", "AB", "ABA", "ABAB", "ABABA"
- Suffixes: "C", "AC", "BAC", "ABAC", "BABAC"
- No overlap ✗
- LPS[5] = 0
Result: LPS = [0, 0, 1, 2, 3, 0]
Algorithm to Build LPS
def compute_lps(pattern):
m = len(pattern)
lps = [0] * m
length = 0 # length of previous longest prefix suffix
i = 1
while i < m:
if pattern[i] == pattern[length]:
# Characters match, extend the LPS
length += 1
lps[i] = length
i += 1
else:
# Mismatch
if length != 0:
# Don't backtrack in text! Use LPS to find next candidate
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
# Example
pattern = "ABABAC"
lps = compute_lps(pattern)
print(lps) # Output: [0, 0, 1, 2, 3, 0]
LPS Construction Trace
Iteration 1 (i=1): 'B' ≠ 'A', length=0 → LPS[1]=0
Iteration 2 (i=2): 'A' = 'A', length=1 → LPS[2]=1
Iteration 3 (i=3): 'B' = 'B', length=2 → LPS[3]=2
Iteration 4 (i=4): 'A' = 'A', length=3 → LPS[4]=3
Iteration 5 (i=5): 'C' ≠ 'B'
⚠️ Mismatch! Here's the key:
- length = lps[4-1] = lps[3] = 2
- 'C' ≠ 'B', so try again
- length = lps[2-1] = lps[1] = 0
- 'C' ≠ 'A', so give up
- LPS[5] = 0
How LPS Enables No Text Backtracking
The Problem Without KMP
Text: ...X A B A B D A B A B A C...
Pattern: A B A B A C
↑ Mismatch at 'D'
Naive approach: Back up text pointer and try again
Text: ...X A B A B D A B A B A C...
Pattern: A B A B A C ← Inefficient! Could waste many comparisons
The KMP Solution with LPS
Text: ...X A B A B D A B A B A C...
Pattern: A B A B A C
Index: 0 1 2 3 4 5
↑
Mismatch at pattern[4]='A' vs text[4]='D'
What LPS tells us (when mismatch at j):
j = 4, so check LPS[j-1] = LPS[3] = 2
This means: The first 2 characters "AB" match the end
of our already-matched text!
Instead of retesting, RESET pattern index to 2:
Pattern reset: A B A B A C
↑ ↑
Start here (no text backtrack!)
Text pointer STAYS at position 4, doesn't move backward!
Complete Matching Example
Text: A B A B D A B A B A B A C
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12
Pattern: A B A B A C
LPS: [0, 0, 1, 2, 3, 0]
Matching process:
t=0,p=0: 'A'='A' ✓ → t=1,p=1
t=1,p=1: 'B'='B' ✓ → t=2,p=2
t=2,p=2: 'A'='A' ✓ → t=3,p=3
t=3,p=3: 'B'='B' ✓ → t=4,p=4
t=4,p=4: 'D'≠'A' ✗ MISMATCH!
Use LPS[3]=2 → reset p to 2
t=4,p=2: 'D'≠'A' ✗ MISMATCH!
Use LPS[1]=0 → reset p to 0
t=4,p=0: 'D'≠'A' ✗ → Advance text: t=5
t=5,p=0: 'A'='A' ✓ → t=6,p=1
t=6,p=1: 'B'='B' ✓ → t=7,p=2
t=7,p=2: 'A'='A' ✓ → t=8,p=3
t=8,p=3: 'B'='B' ✓ → t=9,p=4
t=9,p=4: 'A'='A' ✓ → t=10,p=5
t=10,p=5: 'B'≠'C' ✗ MISMATCH!
Use LPS[4]=3 → reset p to 3
t=10,p=3: 'B'='B' ✓ → t=11,p=4
t=11,p=4: 'A'='A' ✓ → t=12,p=5
t=12,p=5: 'C'='C' ✓ → MATCH FOUND at text index 7!
Note: Text pointer NEVER moved backward (no backtracking!)
Key Insight: Why No Backtracking?
| Aspect | Traditional | KMP with LPS |
|---|
| On Mismatch | Backtrack text pointer | Reuse LPS info, reset pattern |
| Text Accesses | O(n²) worst case | O(n) guaranteed |
| Key Idea | Retry failed search | Self-overlap detection |
The LPS array encodes knowledge about the pattern's internal structure, so when a mismatch occurs, we can "skip" positions we've already verified through the pattern's self-similarity, not by retesting the text.
Time Complexity: O(m + n) where m = pattern length, n = text length (each character examined at most twice)