Sub topic 3
Prefixes, Suffixes, and Borders
This chapter assumes you can read Python, are comfortable with zero-based indexing and string slicing, and have seen why naive search does extra work after a mismatch. The idea introduced here, the border, is what lets KMP skip that extra work.
Prefixes and suffixes
A prefix of a string s is any string you get by keeping the first k characters, s[0:k]. A suffix keeps the last k characters, s[n-k:n], where n = len(s). With k = 0 both are the empty string, and with k = n both are s itself.
A prefix or suffix is proper when it is shorter than s, so k < n. KMP only cares about proper ones. The whole string is trivially a prefix and a suffix of itself, and that tells you nothing useful.
For s = "ababa":
| k | Proper prefix `s[:k]` | Proper suffix `s[n-k:]` | Equal? |
|---|---|---|---|
| 0 | "" | "" | yes |
| 1 | "a" | "a" | yes |
| 2 | "ab" | "ba" | no |
| 3 | "aba" | "aba" | yes |
| 4 | "abab" | "baba" | no |
Borders
A border of s is a string that is both a proper prefix and a proper suffix of s. From the table, the borders of "ababa" are "", "a", and "aba". The longest proper border is "aba", which has length 3.
Notice that the prefix "aba" (positions 0 to 2) and the suffix "aba" (positions 2 to 4) share position 2. Borders are allowed to overlap like this, and overlapping borders are exactly what produce overlapping matches later in the tutorial.
The empty string is a border of every non-empty string, so the longest proper border always exists. Its length is between 0 and n - 1.
Why borders matter for matching
Suppose the first q characters of the pattern matched the text and then the next character failed. The text you just read is pattern[:q]. Naive search shifts the pattern by one and compares those same characters again. A shift can only succeed if the part of the pattern that still overlaps the already-read text agrees with it. That means some prefix of the pattern has to equal a suffix of pattern[:q], which is a border of pattern[:q]. The smallest safe shift lines up the longest border, because a shorter border means a larger jump that could skip an occurrence.
Finding borders by brute force
The direct definition gives a simple check. It is quadratic, which is fine for building intuition. The next chapters replace it with a linear method.
def border_lengths(s):
"""Return lengths of all proper borders of s, longest first."""
n = len(s)
return [k for k in range(n - 1, -1, -1) if s[:k] == s[n - k:]]
print(border_lengths("ababa")) # [3, 1, 0]
print(border_lengths("abacaba")) # [3, 1, 0]
print(border_lengths("aabaaab")) # [3, 0]
print(border_lengths("abc")) # [0]Borders of borders
There is one more fact that the linear algorithm depends on. If b is a border of s, then the borders of b are exactly the borders of s that are shorter than b. So you can list every border of s by taking the longest border, then the longest border of that string, and so on until you reach the empty string.
The chain 3, 1, 0 matches the output of border_lengths("abacaba"). As a result, storing only the longest border length for each prefix of the pattern is enough to recover every border. The prefix function in the next chapter is that stored table.
Common mistakes
- Counting the whole string as a border. Borders must be proper, so
"aaa"has longest border"aa", not"aaa". - Assuming borders cannot overlap. In
"aaaa"the border"aaa"overlaps itself heavily. - Confusing a border with a repeated substring.
"abcxbc"contains"bc"twice, but"bc"is not a prefix, so its longest border is empty.
Exercise
List the lengths of all proper borders of "aaaa", longest first.
Show answer
[3, 2, 1, 0]. Every prefix of "aaaa" made only of a's equals the suffix of the same length, as long as it is shorter than 4.
Exercise
What is the longest proper border of "abcab", and what does the border chain look like?
Show answer
The longest proper border is "ab" (length 2). The longest border of "ab" is the empty string, so the chain is 2, 0.