Sub topic 10
Matching with a Single Prefix Function Pass
This chapter assumes you already know how to compute the prefix function in linear time and how KMP search uses it. It shows a shortcut: you can find every match by computing one prefix function over a single combined string, with no separate search loop.
The Idea
Build a new string s from three parts:
- The pattern, of length
m. - A separator character that appears in neither the pattern nor the text.
- The text, of length
n.
Then compute the prefix function of s. Recall that pi[i] is the length of the longest proper border of s[0..i], meaning the longest prefix of s that also ends at position i. The prefix of s with length m is the pattern itself. So when pi[i] == m at a position inside the text part, the pattern ends at position i.
Why the Separator Matters
The separator caps every pi value at m. A border is a prefix of s, and any prefix longer than m includes the separator. The separator never appears in the text, so no substring ending inside the text can contain it. That means no border can be longer than m.
Without the separator, borders can run past the pattern into the text and grow larger than m, and matches get skipped. Take pattern aa and text aaa. Joined directly, they form aaaaa, whose prefix function is [0, 1, 2, 3, 4]. The value 2 appears only once, at the junction, so the matches at text indices 0 and 1 go uncounted.
Converting Positions
If pi[i] == m, the match ends at index i of s. The text starts at index m + 1 of s, so the match ends at text index i - (m + 1). A match of length m that ends there starts at:
i - (m + 1) - m + 1 = i - 2m
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]A Worked Trace
Pattern abab, text abababca, so m = 4 and s = "abab\0abababca". Here \0 is the separator.
| i | s[i] | pi[i] | Note |
|---|---|---|---|
| 0–3 | a b a b | 0 0 1 2 | the pattern itself |
| 4 | \0 | 0 | the separator resets to 0 |
| 5–7 | a b a | 1 2 3 | |
| 8 | b | 4 | match, start 8 − 8 = 0 |
| 9 | a | 3 | falls back to a border of length 2, then extends |
| 10 | b | 4 | match, start 10 − 8 = 2 |
| 11 | c | 0 | |
| 12 | a | 1 |
At index 9, the fallback through pi[3] = 2 is the same step KMP takes after a match. That fallback is why the overlapping match at 2 is found.
Trade-offs
| Aspect | Concatenation trick | Standard KMP |
|---|---|---|
| Code to write | One function | Two functions |
| Extra memory | O(n + m) for `s` and `pi` | O(m) for `pi` |
| Streaming text | No, the whole text must be in memory | Yes |
| Separator needed | Yes | No |
The trick is handy in contests and quick scripts, and it reuses a function you already trust. For large or streamed texts, standard KMP keeps memory at O(m).
Exercise
Run findwithconcatenation("aaa", "aa") by hand. Write down the prefix function of s and the match positions it returns.
Show answer
s = "aa\0aaa" and pi = [0, 1, 0, 1, 2, 2]. pi equals m = 2 at indices 4 and 5, which gives starts 4 − 4 = 0 and 5 − 4 = 1. The function returns [0, 1], and both overlapping matches are found.
Exercise
Suppose the separator also appears in the text. Give an example where the trick reports a wrong match.
Show answer
Pattern "a#" with separator "#" and text "#a#". Then s = "a##a#", and the border "a#" can now cross the separator. pi[1] = 0 is fine, but in other inputs a border longer than m can form, which hides real matches. In this example the start formula also maps positions incorrectly if the pattern prefix lines up with the separator. A separator absent from both strings rules out every such case.