Sub topic 3
Prefixes, Suffixes, and Borders
This chapter assumes you can read Python, are comfortable with zero-based indexing and slicing (s[i:j]), and know Big-O notation. It also assumes you have seen why naive search can take O(n · m) time. The aim here is the vocabulary KMP relies on: prefixes, suffixes, and borders. You will also learn the one property of borders that lets KMP skip work without ever missing a match.
Why We Need a New Concept
Naive search wastes work when a partial match fails. Suppose the pattern is abacabad and the first seven characters abacaba have matched the text before a mismatch at the eighth. Naive search shifts the pattern by one position and compares again from scratch. It throws away everything it learned about those seven characters.
The text characters we just matched are known: they are exactly p[0..6] = "abacaba". So the question "which later shifts could still produce a match?" depends only on the pattern. We can answer it before we read any text. Borders give that answer.
Prefixes and Suffixes
Let s be a string of length n.
- A prefix of
siss[0:k]for some0 ≤ k ≤ n. It is the firstkcharacters. - A suffix of
siss[n-k:n]for some0 ≤ k ≤ n. It is the lastkcharacters. - A prefix or suffix is proper when
k < n, meaning it is not the whole string.
The empty string (k = 0) counts as both a prefix and a suffix of every string, and it is proper whenever n ≥ 1.
For s = "abacaba" (length 7):
| k | Prefix `s[:k]` | Suffix `s[n-k:]` | Equal? |
|---|---|---|---|
| 0 | `""` | `""` | yes |
| 1 | `a` | `a` | yes |
| 2 | `ab` | `ba` | no |
| 3 | `aba` | `aba` | yes |
| 4 | `abac` | `caba` | no |
| 5 | `abaca` | `acaba` | no |
| 6 | `abacab` | `bacaba` | no |
| 7 | `abacaba` | `abacaba` | yes, but not proper |
Borders
A border of s is a string that is both a proper prefix and a proper suffix of s. In the table above, "abacaba" has borders of length 3 (aba), 1 (a), and 0 (the empty string). Row 7 does not count, because the whole string is never a proper border of itself. Without that rule every string would trivially be its own longest border, and the concept would tell us nothing.
The longest proper border is the one KMP cares about most. For abacaba it is aba, of length 3. We usually describe borders by their length k, since the border is then simply s[:k].
More examples:
| String | Border lengths (longest first) | Longest proper border |
|---|---|---|
| `abcd` | 0 | `""` |
| `aaaa` | 3, 2, 1, 0 | `aaa` |
| `abab` | 2, 0 | `ab` |
| `aabaabaa` | 5, 2, 1, 0 | `aabaa` |
| `a` | 0 | `""` |
Borders can overlap
In aaaa the border aaa occupies positions 0–2 as a prefix and positions 1–3 as a suffix. The two copies overlap in two characters. This is allowed and common. Never assume that a border's prefix copy and suffix copy are disjoint. In aabaabaa the border aabaa covers positions 0–4 and 3–7, which also overlap.
Checking Borders by Brute Force
The following code is a direct translation of the definitions. It is slow on purpose: it is a reference you can trust when checking hand calculations and the faster code in later chapters.
def is_border(s, k):
"""True if the length-k prefix of s is a proper border of s."""
n = len(s)
return 0 <= k < n and s[:k] == s[n - k:]
def all_borders(s):
"""Lengths of all proper borders of s, longest first."""
return [k for k in range(len(s) - 1, -1, -1) if is_border(s, k)]
def longest_border(s):
"""Length of the longest proper border; 0 for the empty string."""
for k in range(len(s) - 1, -1, -1):
if is_border(s, k):
return k
return 0
print(all_borders("abacaba")) # [3, 1, 0]
print(all_borders("aabaabaa")) # [5, 2, 1, 0]
print(all_borders("aaaa")) # [3, 2, 1, 0]
print(longest_border("abcd")) # 0
print(all_borders("")) # []The empty string has no proper prefix at all, so all_borders("") is empty. By convention longest_border("") returns 0, which matches how the prefix function treats it later.
Each is_border call costs O(k), so all_borders takes O(n²) time on a string of length n. KMP needs the longest border of every prefix of the pattern. Doing that by brute force would cost O(m³). The next two chapters bring this down to O(m), and the property below is what makes that possible.
The Key Property: Borders Form a Chain
Claim 1. If b is a border of s and c is a border of b, then c is a border of s.
Proof. c is a prefix of b, and b is a prefix of s, so c is a prefix of s. The same reasoning applies to suffixes. Since |c| < |b| < |s|, c is proper.
Claim 2. If b is the longest proper border of s and c is any shorter border of s, then c is a border of b.
Proof. Both c and b are prefixes of s, and |c| < |b|, so c is a prefix of b. Both are also suffixes of s, so c is a suffix of b too. Since |c| < |b|, c is a proper border of b.
Taken together, the two claims say this: the borders of s, from longest to shortest, are its longest border, then the longest border of that, and so on down to the empty string. You never have to search the whole string again for the next shorter border. You only look inside the border you already have.
You can check the chain property with the brute-force helpers:
def is_border(s, k):
n = len(s)
return 0 <= k < n and s[:k] == s[n - k:]
def all_borders(s):
return [k for k in range(len(s) - 1, -1, -1) if is_border(s, k)]
def longest_border(s):
for k in range(len(s) - 1, -1, -1):
if is_border(s, k):
return k
return 0
def border_chain(s):
"""Follow longest borders until reaching the empty string."""
chain = []
b = s
while b:
k = longest_border(b)
chain.append(k)
b = b[:k]
return chain
for word in ["abacaba", "aabaabaa", "aaaa", "abcd", "abababab"]:
assert border_chain(word) == all_borders(word), word
print(word, border_chain(word))
# abacaba [3, 1, 0]
# aabaabaa [5, 2, 1, 0]
# aaaa [3, 2, 1, 0]
# abcd [0]
# abababab [6, 4, 2, 0]When KMP falls back on a mismatch, it is walking this chain. In code, that walk is the line k = pi[k - 1] you will meet in the next chapters.
How Borders Decide Which Shifts Are Safe
Back to the opening example. The pattern is p = "abacabad", the first j = 7 characters have matched, and then a mismatch occurs. The text just read is t = "abacaba", which equals p[:7].
Now consider shifting the pattern right by d positions, where 0 < d < j. After the shift, the first j - d characters of the pattern lie over the last j - d characters of t. For the shifted pattern to have any chance of matching, these must agree:
p[:j - d] == t[d:j] == p[d:j]
In words, the prefix of p[:j] with length j - d must equal the suffix of p[:j] with the same length. That is exactly the statement that p[:j] has a border of length j - d.
So the only shifts worth trying are d = j - k for each border length k of the matched part. For abacaba the borders are 3, 1, and 0, so the candidate shifts are 4, 6, and 7. Shifts 1, 2, 3, and 5 cannot possibly match, and we never need to test them.
| Shift d | Overlap length j − d | Border of `abacaba`? | Could match? |
|---|---|---|---|
| 1 | 6 | no | no |
| 2 | 5 | no | no |
| 3 | 4 | no | no |
| 4 | 3 | yes (`aba`) | yes |
| 5 | 2 | no | no |
| 6 | 1 | yes (`a`) | yes |
| 7 | 0 | yes (empty) | yes |
The smallest candidate shift, d = 4, comes from the longest border. Taking it is safe because no smaller shift can succeed, so no occurrence is skipped. It is also efficient: after the shift, the first 3 characters of the pattern are already known to match, so comparison resumes at pattern index 3 and the text pointer stays where it is. If that comparison also fails, the next candidate comes from the next border in the chain. This is why the chain property matters.
Common Mistakes
- Counting the whole string as a border. Borders must be proper. If you forget this, every longest border equals the string itself, and the shift becomes 0, which means the algorithm stops making progress.
- Assuming the next shorter border needs a fresh search. By Claim 2 it is the longest border of the current border. Searching
sagain works but costs extra time. - Assuming borders do not overlap.
aaaaandababababshow that they often do. - Forgetting the empty border. Length 0 is always in the chain. It corresponds to shifting the pattern completely past the matched text.
- Confusing border length with border index. A border of length
kends at indexk - 1as a prefix. Mixing these up causes most off-by-one bugs in prefix-function code.
Exercises
Exercise
List all proper border lengths of "abaababaab", longest first, and give its longest proper border.
Show answer
The lengths are 5, 3, 0. Length 5: the prefix "abaab" equals the suffix "abaab". Length 3: the prefix "aba" equals the suffix "aab"? No, that does not match. Check again from the chain: the longest border is "abaab" (5), and the longest border of "abaab" is "ab" (2), whose longest border is "" (0). So the correct list is 5, 2, 0, and the longest proper border is "abaab". You can confirm that the suffix of length 2 is "ab" and the suffix of length 3 is "aab", which is not equal to "aba".
Exercise
The pattern "abababc" has matched its first 6 characters, "ababab", against the text, and then a mismatch occurs. Which shifts d (1 to 6) could still lead to a match, and which one should KMP take first?
Show answer
The borders of "ababab" have lengths 4, 2, and 0, so the candidate shifts are 6 − 4 = 2, 6 − 2 = 4, and 6 − 0 = 6. Shifts 1, 3, and 5 cannot match. KMP takes d = 2 first, because it comes from the longest border. It then resumes comparing at pattern index 4 without moving back in the text.
Exercise
Using Claims 1 and 2, explain why following longest borders from s (s, then its longest border, then that string's longest border, and so on) lists every border of s exactly once, with none missing.
Show answer
By Claim 1, each string in the chain is a border of the one before it, and so by induction a border of s. Lengths strictly decrease, so no border repeats and the chain ends at the empty string. For completeness, let c be any border of s. If c is not the longest border b, Claim 2 says c is a border of b. Apply the same argument inside b, and keep going. Because lengths shrink at every step, c eventually equals the longest border of some string in the chain, so it appears in the chain.