Skip to contentKEEP THE CRAFTTHE SANCTUARY

Knuth-Morris-Pratt

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 Code Labs

Precompute Prefix Suffix Fallbacks

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.

Advance without Rechecking Text

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.

Trace KMP Prefix Function

Reference
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 trace
Practice

Implement prefix_trace(pattern). Return [index,fallbacks,prefix_length] for each index after the first.

Public tests

  • Fallback through proper prefix lengths

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace KMP Prefix Function

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 trace

Fallback and Recompare the Same Final Character

Predict 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.
Print 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.

Fallback the Pattern on Mismatch

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.

Find All KMP Matches

Reference
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 matches
Practice

Implement kmp_indexes(text,pattern). Return all start indexes including overlaps; empty pattern matches at every boundary.

Public tests

  • Reuse fallback after overlapping matches

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find All KMP Matches

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 matches

Handle Overlapping Matches

After 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.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Prefix constructionO(m)O(m)Each extension increases length and each fallback decreases it; the total decreases are bounded by prior increases.
All-match searchO(n+m+k)O(n+m+k)k is output count; text advances n times and fallback work is amortized.

Space

O(m+k) prefix table and returned indexes; prefix trace stores O(m) rows and total fallback events.

Assumptions

  • For empty pattern, the all-match Lab returns n+1 boundaries.
  • The prefix trace records fallback lengths before their reduction, not indexes of mismatching text.

Invariants Worth Saying Aloud

  1. prefix[i] is the length of the longest proper border of pattern[:i+1].
  2. During search, length identifies a pattern prefix matching the suffix of consumed text.
  3. Fallback reduces length while retaining the current unconsumed text symbol.

When To Use Or Avoid Knuth-Morris-Pratt

Use It When

  • Use a prefix table to preserve already matched suffix information.
  • After a full match, fall back to the final proper border to discover overlaps.

Choose Another Tool When

  • A short one-off pattern may be easier to handle with the standard string search API.
  • KMP matches exact symbol sequences; it does not by itself normalize Unicode or tokenize graphemes.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Resetting to zero instead of retaining a shorter border

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.

Avoid

length=0

Use instead

length=prefix[length-1]

Using the border length as the table index

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.

Avoid

length=prefix[length]

Use instead

length=prefix[length-1]

Keeping the full matched length for the next symbol

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.

Avoid

length=len(prefix)

Use instead

length=prefix[-1]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.