Sub topic 7
Edge Cases and Overlapping Matches
This chapter assumes you have already seen prefix_function and kmp_search from the earlier chapters. You should be comfortable reading Python and tracing a loop by hand. The goal here is to check the search on inputs that often break string matchers: overlapping occurrences, an empty pattern, a pattern longer than the text, and empty text.
Here is the full implementation again, so you can run it as shown:
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 kmp_search(text, pattern):
m = len(pattern)
if m == 0:
return list(range(len(text) + 1))
pi = prefix_function(pattern)
matches = []
k = 0
for i, c in enumerate(text):
while k > 0 and c != pattern[k]:
k = pi[k - 1]
if c == pattern[k]:
k += 1
if k == m:
matches.append(i - m + 1)
k = pi[k - 1]
return matches
print(kmp_search("aaaa", "aa")) # [0, 1, 2]
print(kmp_search("abc", "")) # [0, 1, 2, 3]
print(kmp_search("ab", "abcd")) # []
print(kmp_search("", "a")) # []
print(kmp_search("", "")) # [0]Overlapping Matches
Two occurrences overlap when the second one starts before the first one ends. In "aaaa" the pattern "aa" occurs at 0, 1, and 2, and each occurrence shares a character with the next.
The line that handles this is k = pi[k - 1] after a full match. A full match means the whole pattern ends at position i. The longest proper border of the pattern is also the longest prefix of the pattern that could start a new match inside the one just found. Falling back to pi[m - 1] keeps that prefix "already matched" instead of discarding it.
Trace for pattern = "aa", where pi = [0, 1]:
| i | c | k after step | Action |
|---|---|---|---|
| 0 | a | 1 | extend |
| 1 | a | 2 → 1 | match at 0, fall back to pi[1] = 1 |
| 2 | a | 2 → 1 | match at 1, fall back |
| 3 | a | 2 → 1 | match at 2, fall back |
The fallback also keeps the index safe. Without it, k would reach m and the next comparison pattern[k] would raise IndexError. Resetting to pi[m - 1] < m keeps k in the range 0..m-1 at the start of every iteration.
The Empty Pattern
With m == 0, the main loop would evaluate pattern[0] and crash, so the function needs a guard. The question is what to return. The usual convention, followed by Python's "abc".find("") returning 0, is that the empty string occurs at every position from 0 to n, which gives n + 1 positions. The guard returns exactly that list.
Some libraries instead return [] or raise an error. Pick one behavior, document it, and test it. Never let it come from an accidental exception.
Pattern Longer Than Text
When m > n, k can grow by at most one per text character, so it never reaches m. The function correctly returns [] with no special case. The only cost is computing pi for a pattern that can never match. If that matters, add if m > len(text): return [] after the empty-pattern guard.
Empty Text
For empty text the loop body never runs. A non-empty pattern gives [], and the empty pattern gives [0] through the guard. Both are consistent with the conventions above.
Exercise
What does kmp_search("abababab", "abab") return, and what would it return if the line after a match were changed to k = 0?
Show answer
With k = pi[m - 1] it returns [0, 2, 4], because pi for "abab" is [0, 0, 1, 2], so after each match k falls back to 2 and the overlapping "ab" is kept. With k = 0 it returns [0, 4], because the scan restarts from scratch after each match and misses the occurrence at 2.
Exercise
Why does the main loop never index past the end of pattern, even though the only explicit length check is k == m?
Show answer
At the start of each iteration k is at most m - 1. Inside the iteration, k grows by at most one, so it can reach m but not exceed it. When it reaches m, it is immediately reset to pi[m - 1], which is less than m. So pattern[k] is always read with k < m, as long as m > 0, which the empty-pattern guard ensures.