Sub topic 7
Edge Cases and Overlapping Matches
The KMP search from the previous chapter works on ordinary inputs. Real inputs are not always ordinary. Patterns can be empty, texts can be shorter than patterns, and occurrences can overlap. Callers may also expect str.count semantics, case-insensitive matching, or matching over lists instead of strings. This chapter goes through each of these cases, shows where a careless implementation breaks, and ends with a test harness that checks KMP against brute force.
This chapter assumes you can read the prefix_function and kmp_search code from the earlier chapters and know that pi[k - 1] is the length of the longest proper border of pattern[0..k-1].
The Hardened Implementation
Here is the version we will analyze. It adds two guard clauses and an overlapping flag to the search from the previous chapter.
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, overlapping=True):
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
if m > n:
return []
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] if overlapping else 0
return matches
print(kmp_search("aaaa", "aa")) # [0, 1, 2]
print(kmp_search("aaaa", "aa", overlapping=False)) # [0, 2]
print(kmp_search("abc", "")) # [0, 1, 2, 3]
print(kmp_search("ab", "abc")) # []The diagram below shows the order in which the function handles each case.
The Empty Pattern
What goes wrong without a guard
If you remove the m == 0 check, prefix_function("") returns []. That part is harmless. The scan then reads the first character, skips the while loop because k == 0, and evaluates pattern[0], which raises IndexError. On an empty text the loop never runs and the function returns []. So the unguarded function crashes on some inputs and returns an answer on others, and neither result is a deliberate choice.
Choosing a convention
The empty string is a prefix of every string, so mathematically it occurs at every position from 0 to n inclusive, which is n + 1 positions. Python agrees:
print("abc".find("")) # 0
print("abc".count("")) # 4
print([i for i in range(len("abc") + 1) if "abc"[i:i] == ""]) # [0, 1, 2, 3]Returning list(range(n + 1)) matches this convention and matches the brute-force naive_search, which also yields every index when m == 0. Some libraries make a different choice: they return no matches, or they raise ValueError because an empty search is usually a bug in the caller. All three choices can be defended. What matters is that you pick one on purpose, document it, and test it.
Pattern Longer Than the Text
KMP is already correct when m > n. The value of k grows by at most one per text character, so after reading i + 1 characters, k ≤ i + 1 ≤ n < m. The condition k == m can never be true, and the function returns [].
The m > n guard is therefore an optimization, not a correctness fix. It skips the O(m) cost of building pi, which matters when someone searches a short text for a very long pattern. It also makes the intent obvious to a reader.
The empty text is a special case of this one. With n == 0 and m ≥ 1, the guard returns []. With n == 0 and m == 0, the first guard returns [0], because the empty string occurs once inside the empty string.
Overlapping Matches
Why the reset uses `pi[m - 1]`
When k reaches m, the last m characters of the text equal the whole pattern. The next occurrence might start inside this one. That happens exactly when the pattern has a border: a proper prefix that is also a suffix. Setting k = pi[m - 1] keeps the longest such border as matched progress, so the scan continues as if that much of the next occurrence had already been read.
Here is the trace for text "aaaa" and pattern "aa", where pi = [0, 1].
| i | c | k after extend | k == m? | Recorded | k after reset |
|---|---|---|---|---|---|
| 0 | a | 1 | no | 1 | |
| 1 | a | 2 | yes | 0 | pi[1] = 1 |
| 2 | a | 2 | yes | 1 | 1 |
| 3 | a | 2 | yes | 2 | 1 |
Every position from 0 to 2 is reported. Each match reuses the single a kept by the reset.
The forgotten reset
A common bug is to record the match and leave k unchanged. On the next character, the while condition or the if evaluates pattern[m], which is out of range, so the code raises IndexError. If the match ends at the last character of the text, the loop finishes before that happens, so the bug only appears when there is text after a match. Tests that only use patterns at the end of the text will miss it.
Non-overlapping semantics
str.count, str.replace, and re.findall do not count overlapping occurrences. They find the leftmost match, skip past it, and continue. "aaaa".count("aa") returns 2, not 3.
To get this behavior, reset k = 0 after a match. The correctness argument is short. The next acceptable match must start at index i + 1 or later. Starting with k = 0 at i + 1 is the same as running fresh KMP on the suffix text[i + 1:], and fresh KMP finds the leftmost occurrence in that suffix. Repeating this step produces the greedy left-to-right sequence that Python's built-ins use.
| Mode | Reset after match | `"aaaa"`, `"aa"` | `"abababa"`, `"aba"` |
|---|---|---|---|
| Overlapping | `k = pi[m - 1]` | `[0, 1, 2]` | `[0, 2, 4]` |
| Non-overlapping | `k = 0` | `[0, 2]` | `[0, 4]` |
Patterns with no border, such as "abc", have pi[m - 1] == 0, so the two modes behave the same. Patterns made of one repeated character have the largest possible border, m - 1, so they produce the most overlaps.
Inputs That Are Not Plain ASCII Strings
Arbitrary sequences
KMP only needs indexing, length, and equality tests. It never hashes characters, uses an alphabet size, or compares characters by order. The same function works on lists of tokens, integers, or tuples:
print(kmp_search([1, 2, 1, 2, 1], [1, 2, 1])) # [0, 2]
print(kmp_search(["GET", "/a", "GET", "/a"], ["GET", "/a"])) # [0, 2]This is an advantage over Boyer-Moore's bad-character table and Rabin-Karp's rolling hash, which both need more structure from the alphabet.
Case folding changes indices
A common way to do case-insensitive matching is to fold both strings and then search. Folding can change the length of a string, and then the reported indices no longer point into the original text:
text = "Straße"
folded = text.casefold() # "strasse", length 7
print(len(text), len(folded)) # 6 7
print(kmp_search(folded, "e")) # [6]
print(text[6:7]) # '' : index 6 is past the end of the originalIf you need positions in the original text, either compare characters with a per-character fold that keeps length (str.lower keeps length for most scripts, but not all), or build an index map from folded positions back to original positions while folding.
Unicode normalization
"é" can be stored as one code point (U+00E9) or as "e" followed by a combining accent (U+0301). KMP compares code points, so these two forms do not match. Normalize both strings with unicodedata.normalize("NFC", s) before searching if the input can come in either form. Normalization can also change length, so the same index-mapping caveat applies.
Testing Against Brute Force
Edge cases are where hand-picked tests fail. Randomized differential testing compares KMP with an implementation that is obviously correct, over thousands of small inputs. A two-letter alphabet makes borders and overlaps very common, and allowing lengths of zero exercises the guard clauses.
import random
def naive_search(text, pattern):
n, m = len(text), len(pattern)
return [i for i in range(n - m + 1) if text[i:i + m] == pattern]
def naive_non_overlapping(text, pattern):
if not pattern:
return list(range(len(text) + 1))
result, i = [], 0
while i <= len(text) - len(pattern):
if text[i:i + len(pattern)] == pattern:
result.append(i)
i += len(pattern)
else:
i += 1
return result
def random_test(trials=20000, seed=42):
rng = random.Random(seed)
for _ in range(trials):
text = "".join(rng.choice("ab") for _ in range(rng.randint(0, 12)))
pattern = "".join(rng.choice("ab") for _ in range(rng.randint(0, 5)))
assert kmp_search(text, pattern) == naive_search(text, pattern), (text, pattern)
non_ov = kmp_search(text, pattern, overlapping=False)
assert non_ov == naive_non_overlapping(text, pattern), (text, pattern)
assert len(non_ov) == text.count(pattern), (text, pattern)
print("all tests passed")
random_test()Run this with the prefix_function and kmp_search definitions from the start of the chapter. The final assertion checks the non-overlapping mode against Python's own str.count, including the empty-pattern case, where both give n + 1. When an assertion fails, it prints the (text, pattern) pair that broke it, which is usually only a few characters long and easy to trace by hand.
Exercise
Pattern "abab" is searched in text "abababab". List the matches in overlapping mode and in non-overlapping mode, and give the value k is reset to after each overlapping match.
Show answer
pi for "abab" is [0, 0, 1, 2], so pi[m - 1] = 2. Overlapping mode finds [0, 2, 4] and resets k to 2 after each match, keeping "ab" as progress. Non-overlapping mode resets k to 0 and finds [0, 4].
Exercise
Someone deletes the line "k = pi[k - 1] if overlapping else 0" from kmpsearch. For which of these calls does the function raise IndexError: kmpsearch("xab", "ab"), kmpsearch("abx", "ab"), kmpsearch("ab", "ab")?
Show answer
Only kmp_search("abx", "ab"). There, k reaches 2 at index 1, and reading "x" at index 2 evaluates pattern[2] in the while condition. In "xab" and "ab" the match ends on the last character, so the loop finishes before pattern[m] is read, and both calls return the correct answer. That is why tests need text after a match.
Exercise
Prove that without the m > n guard, kmp_search still returns [] whenever the pattern is longer than the text. Then explain what the guard saves.
Show answer
Each loop iteration raises k by at most 1 and the while loop only lowers it, so after processing index i, k ≤ i + 1 ≤ n. Since n < m, k never equals m and nothing is recorded. The guard skips building the prefix function, saving O(m) time and memory when the pattern is long and the text is short.