Sub topic 10
Matching with a Single Prefix Function Pass
In the previous chapters, KMP search ran as two separate steps. First you computed the prefix function of the pattern, then you ran a second loop over the text that used that table. This chapter shows a shorter route. You join the pattern, a separator character, and the text into one string, then compute the prefix function of that combined string. Every position where the value equals the pattern length marks the end of a match.
This chapter assumes you already know these things:
- The prefix function
pi, wherepi[i]is the length of the longest proper border ofs[0..i]. - The linear-time
prefix_functionroutine from the chapter on computing it. - The KMP search loop, including how it resets
kafter a match.
The Idea
Let m = len(pattern) and n = len(text). Build:
s = pattern + sep + textHere sep is a character that appears in neither pattern nor text. Now compute pi = prefix_function(s).
Take any position i inside the text part of s. The value pi[i] is the length of the longest prefix of s that also ends at position i. Every prefix of s that is no longer than m is a prefix of pattern. So when pi[i] == m, the whole pattern ends at position i of s, and that is a match in the text.
The separator does two jobs:
- It stops a border from growing past
m, sopi[i]never exceedsm. "Equal tom" then means exactly "the full pattern ends here." - It stops a match from crossing the boundary between pattern and text, so no false match can begin inside the copy of the pattern.
The Code
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def find_with_concatenation(text, pattern, sep="\0"):
m = len(pattern)
s = pattern + sep + text
pi = prefix_function(s)
return [i - 2 * m for i in range(len(s)) if pi[i] == m]
print(find_with_concatenation("abababca", "abab")) # [0, 2]The list comprehension scans every index of s, including the pattern part. That is safe for any non-empty pattern. Inside s[0..m-1] the value pi[i] is a proper border of a pattern prefix, so it is at most i < m and can never equal m. At the separator, pi[m] is 0. Only text positions can report a match.
Converting the Index
The formula i - 2m causes the most off-by-one bugs, so here is the derivation.
- Text index
jis stored ats[m + 1 + j]. The offset ismpattern characters plus one separator. - If
pi[i] == m, the match ends ats[i], which is text indexi - m - 1. - A match of length
mthat ends at text indexestarts ate - m + 1. - So the start is
(i - m - 1) - m + 1 = i - 2m.
A Worked Trace
Use pattern = "abab" and text = "abababca". For readability, # stands in for the separator. Here m = 4.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| s[i] | a | b | a | b | # | a | b | a | b | a | b | c | a |
| pi[i] | 0 | 0 | 1 | 2 | 0 | 1 | 2 | 3 | 4 | 3 | 4 | 0 | 1 |
Some steps to check by hand:
- At
i = 8,kreaches 4, sopi[8] = 4 = m. The match starts at8 - 8 = 0. - At
i = 9, the routine comparess[9] = 'a'withs[4] = '#'. They differ, sokfalls back topi[3] = 2. Thens[2] = 'a'matches, andpi[9] = 3. - At
i = 10,pi[10] = 4 = m. The match starts at10 - 8 = 2. It overlaps the first match. - At
i = 11,'c'forceskdown through 2 and then 0, sopi[11] = 0.
The result is [0, 2], the same answer kmp_search gives.
Why This Is the Same as KMP
Look at what happened at i = 9. After a full match, k = m, and the next comparison is against s[m], the separator. That comparison always fails, so k falls back to pi[m - 1]. This is the reset that kmp_search performs explicitly with k = pi[k - 1] after it records a match.
So the two methods perform the same comparisons in the same order:
- The pattern part of the pass computes the pattern's prefix function.
- The text part of the pass is the KMP search loop.
- The separator acts as a built-in "reset after match" step.
That is also why overlapping matches come out correctly with no extra code. The running time is O(n + m), by the same amortized argument as before, because this is one prefix function computation on a string of length n + m + 1.
Why the Separator Is Required
Remove the separator and two kinds of errors show up.
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def broken_no_sep(text, pattern):
m = len(pattern)
s = pattern + text
pi = prefix_function(s)
# without a separator, text index j sits at s[m + j],
# so a match ending at s[i] starts at i - 2m + 1
return [i - 2 * m + 1 for i in range(m, len(s)) if pi[i] == m]
print(broken_no_sep("aa", "a")) # [] but the correct answer is [0, 1]
print(broken_no_sep("a", "aa")) # [-1], a match that does not exist- Missed matches. With
pattern = "a"andtext = "aa",s = "aaa"andpi = [0, 1, 2]. The value at the end grows to 2, which is longer than the pattern, so the testpi[i] == mskips it. Borders that run pastmhide real matches. - False matches. With
pattern = "aa"andtext = "a",s = "aaa"andpi[2] = 2. The reported "match" uses one character from the pattern copy and one from the text. The text holds only one character, so no match exists.
With a separator, a border longer than m would need the separator inside both its prefix and its suffix. The separator occurs only once, at index m, so that cannot happen. This argument relies on the separator being absent from both strings.
A Separator That Can Never Collide
prefix_function only compares elements with == and !=, so it works on any sequence. Turn both strings into lists and insert a unique object as the separator. A fresh object() compares unequal to every string, so a collision is impossible. This also lets you match sequences of tokens, words, or numbers.
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def find_in_sequence(text, pattern):
m = len(pattern)
sentinel = object()
s = list(pattern) + [sentinel] + list(text)
pi = prefix_function(s)
return [i - 2 * m for i in range(len(s)) if pi[i] == m]
print(find_in_sequence("a\0a\0a", "a\0a")) # [0, 2]
words = "to be or not to be".split()
print(find_in_sequence(words, ["to", "be"])) # [0, 4]The first call would fail with the "\0" separator, because the text itself contains NUL characters.
Edge Cases
- Empty pattern. With
m = 0,s = sep + text. No non-empty prefix ofscan be a border, because every prefix starts with the separator and the separator appears only once. So everypi[i]is 0, which equalsm, and the function returns[0, 1, ..., n]. This matches the convention inkmp_search: the empty pattern occurs at every one of then + 1positions. - Pattern longer than text.
pi[i]can only reachmaftermtext characters have been read, so the result is an empty list. No special case is needed. - Empty text.
sis the pattern followed by the separator, so the result is empty whenm > 0and[0]whenm = 0.
When to Use the Trick
| Aspect | Separate KMP search | Concatenation trick |
|---|---|---|
| Time | O(n + m) | O(n + m) |
| Extra memory | O(m) for the pattern's table | O(n + m) for the full `pi` array and `s` |
| Works on a stream of text | Yes, one character at a time | No, the whole text must be in memory |
| Code to write | Two loops | One existing routine plus one line |
| Needs a separator | No | Yes, and it must be absent from the input |
The trick is a good fit for contests, quick scripts, and any setting where you already have a tested prefix_function and the text fits in memory. Use the separate KMP loop when the text is large, arrives as a stream, or you cannot guarantee a safe separator. The two methods do the same work. The separate loop just keeps only the current k for the text instead of storing a pi value for every text position.
Exercises
Exercise
For pattern "aa" and text "aaaa", using "#" as the separator, write out s and its prefix function, then list the match positions that findwithconcatenation returns.
Show answer
s = "aa#aaaa" and pi = [0, 1, 0, 1, 2, 2, 2]. With m = 2, pi[i] == 2 at i = 4, 5, 6, which gives starts 4 - 4 = 0, 5 - 4 = 1, and 6 - 4 = 2. The result is [0, 1, 2], and it includes all the overlapping matches.
Exercise
A teammate writes s = pattern + sep + text and reports matches at i - m - 1. What do they actually get, and what is the fix?
Show answer
i - m - 1 is the text index where the match ends, not where it starts. For any m greater than 1 every result is too large by m - 1. Use i - 2m, which subtracts a further m - 1 to move from the end of the match to its start.
Exercise
Two strings a and b of equal length are rotations of each other if b occurs in a + a. Using findwithconcatenation, write a one-line check is_rotation(a, b), and say why the length check is needed.
Show answer
return len(a) == len(b) and len(findwithconcatenation(a + a, b)) > 0. Without the length check, any substring of a + a would pass. For example, "ab" occurs in "abcabc", but "ab" is not a rotation of "abc".
Exercise
Explain why pi[i] can never exceed m when the separator appears in neither string.
Show answer
A border of length L > m would make s[0..L-1], which contains the separator at index m, equal to the suffix ending at i. That suffix would then need the separator at index i - L + 1 + m. Because a proper border starts after index 0, that index is greater than m. The separator occurs only at index m, so no such border can exist.