Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Knuth-Morris-Pratt proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Reuse the longest proper prefix that is also a suffix to continue after mismatch or a complete match. Keep the current text symbol during fallback and preserve overlaps without retreating the text index.
1 practice exercise1 interview problem
Recognize it when Repeated pattern prefixes cause many restarts in a naive matcher.
Checking your account…
Knuth-Morris-Pratt (KMP) builds a prefix table where each position stores the longest proper pattern prefix that is also a suffix ending there. This records reusable partial-match structure.
The text index never moves backward. After a mismatch, already matched text remains useful because the prefix table identifies the next pattern alignment consistent with that suffix.
def prefix_trace(pattern):
prefix=[0]*len(pattern);trace=[]
for index in range(1,len(pattern)):
length=prefix[index-1];fallbacks=[]
while length and pattern[index]!=pattern[length]:fallbacks.append(length);length=prefix[length-1]
if pattern[index]==pattern[length]:length+=1
prefix[index]=length;trace.append([index,fallbacks,length])
return traceImplement prefix_trace(pattern). Return [index,fallbacks,prefix_length] for each index after the first.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def prefix_trace(pattern):
prefix=[0]*len(pattern);trace=[]
for index in range(1,len(pattern)):
length=prefix[index-1];fallbacks=[]
while length and pattern[index]!=pattern[length]:fallbacks.append(length);length=prefix[length-1]
if pattern[index]==pattern[length]:length+=1
prefix[index]=length;trace.append([index,fallbacks,length])
return tracePredict the final row before running the existing prefix Lab. The recorded fallback [2] and the final length 2 are not contradictory: a shorter border survives and then grows again using the same symbol.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Load prior border | length=prefix[index-1];fallbacks=[] |
index=1, length=0 |
The first position has no nonempty proper border. |
| Extend first border | if pattern[index]==pattern[length]:length+=1 |
index=1, length=1 |
The two initial a symbols share a one-symbol proper border. |
| Record first result | prefix[index]=length;trace.append([index,fallbacks,length]) |
row=[1,[],1] |
The record is outside the conditional, so both successful and unsuccessful comparisons can produce rows. |
| Mismatch at b | fallbacks.append(length);length=prefix[length-1] |
index=2: fallbacks=[1], length=0 |
b cannot extend the one-a border; retry the first pattern symbol before deciding whether to grow. |
| Record mismatch | prefix[index]=length;trace.append([index,fallbacks,length]) |
row=[2,[1],0] |
b also differs from the first a, so the final length stays zero. |
| Rebuild later border | if pattern[index]==pattern[length]:length+=1 |
after the comparisons at indexes 3 and 4: lengths 1 then 2 |
Each iteration loads its prior prefix length; matching a symbols reconstruct aa. |
| Final fallback | fallbacks.append(length);length=prefix[length-1] |
index=5: old length 2 falls to 1 |
The same a mismatches pattern[2]=b, but the shorter border remains eligible. |
| Retry current symbol | if pattern[index]==pattern[length]:length+=1 |
index=5: length grows from 1 to 2 |
No text symbol is discarded; the shorter border permits the current a to extend again. |
| Record final result | prefix[index]=length;trace.append([index,fallbacks,length]) |
row=[5,[2],2] |
The recorded fallback length and final length describe different moments in the same iteration. |
| Output | |
|---|---|
print(prefix_trace("aabaaa")) |
[[1, [], 1], [2, [1], 0], [3, [], 1], [4, [], 2], [5, [2], 2]] |
In search, the same principle preserves a suffix of consumed text. Amortized accounting applies to total movement of length, rather than claiming that each possible prefix length can only appear once.
While matched length is positive and the next symbols differ, replace length with the prefix value before it. If symbols then match, extend by one; do not discard the current text symbol prematurely.
def kmp_indexes(text,pattern):
if pattern=="":return list(range(len(text)+1))
prefix=[0]*len(pattern)
for index in range(1,len(pattern)):
length=prefix[index-1]
while length and pattern[index]!=pattern[length]:length=prefix[length-1]
if pattern[index]==pattern[length]:length+=1
prefix[index]=length
matches=[];length=0
for index,character in enumerate(text):
while length and character!=pattern[length]:length=prefix[length-1]
if character==pattern[length]:length+=1
if length==len(pattern):matches.append(index-len(pattern)+1);length=prefix[length-1]
return matchesImplement kmp_indexes(text,pattern). Return all start indexes including overlaps; empty pattern matches at every boundary.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def kmp_indexes(text,pattern):
if pattern=="":return list(range(len(text)+1))
prefix=[0]*len(pattern)
for index in range(1,len(pattern)):
length=prefix[index-1]
while length and pattern[index]!=pattern[length]:length=prefix[length-1]
if pattern[index]==pattern[length]:length+=1
prefix[index]=length
matches=[];length=0
for index,character in enumerate(text):
while length and character!=pattern[length]:length=prefix[length-1]
if character==pattern[length]:length+=1
if length==len(pattern):matches.append(index-len(pattern)+1);length=prefix[length-1]
return matchesAfter a full match, record its start and fall back using the final prefix value rather than resetting to zero. This permits overlapping occurrences such as aba inside ababa.
Say: “The prefix table tells how much of the pattern remains valid after mismatch. Text never retreats, and the total fallback decrease is bounded by prior increases as text advances. The same prefix length can appear repeatedly.” State empty-pattern and overlapping-match semantics and O(n + m) time.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Knuth-Morris-Pratt proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Prefix construction | O(m) | O(m) | Each extension increases length and each fallback decreases it; the total decreases are bounded by prior increases. |
| All-match search | O(n+m+k) | O(n+m+k) | k is output count; text advances n times and fallback work is amortized. |
O(m+k) prefix table and returned indexes; prefix trace stores O(m) rows and total fallback events.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
For aabaaa at the final a, border length 2 falls back to length 1, which can still extend to 2. Resetting throws that match away.
Prevent it: Set length to prefix[length-1] and compare the same symbol again.
length=0length=prefix[length-1]Where you will hit this: Build a KMP Prefix Table(opens in a new tab)
The previous matched prefix ends at length-1. Reading prefix[length] examines a different prefix and can fail to decrease length.
Prevent it: Read the entry immediately before the matched-length boundary.
length=prefix[length]length=prefix[length-1]Where you will hit this: Build a KMP Prefix Table(opens in a new tab)
After all three symbols of aba match, length 3 points past the pattern. Retaining it for the next symbol raises IndexError instead of preserving the proper overlapping border.
Prevent it: Fall back to the final proper border after reporting the match, before reading another pattern symbol.
length=len(prefix)length=prefix[-1]Where you will hit this: Lowest Common Ancestor in a BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27