Sub topic 9
Proving Linear Running Time
This chapter assumes you already know the prefix function code and the KMP search loop from the earlier chapters. You should also be comfortable with Big-O notation. The aim is to show why KMP runs in O(n + m) time, where n is the text length and m is the pattern length, even though its inner while loop can run many times on a single character.
The worry: a loop inside a loop
The search has a for loop over the text and a while loop inside it that falls back through borders. If you only look at the loop structure, the bound seems to be O(n · m), since one character could trigger up to m fallbacks. That bound is correct but loose. A single character can trigger many fallbacks, but the total number of fallbacks across the whole run is small. The tool for showing this is an amortized argument. An amortized argument bounds the total cost of a sequence of operations instead of the worst cost of each operation.
The potential: the variable k
Both the prefix function and the search keep one integer, k, which is the length of the current matched prefix. Track how k changes:
| Event | Effect on k | How often |
|---|---|---|
| Characters match (`k += 1`) | increases by exactly 1 | at most once per `for` iteration |
| Fallback (`k = pi[k - 1]`) | decreases by at least 1 | any number of times per iteration |
| Reset after a full match | decreases by at least 1 | at most once per iteration |
| Starting value | k = 0 | once |
The fallback always shrinks k because pi[k - 1] is the length of a proper border of a string of length k, so pi[k - 1] < k. Also, k can never go below 0.
The counting argument
kstarts at 0 and goes up by at most 1 per character of the text. Over the whole search, the total increase is at most n.- Each fallback lowers
kby at least 1. knever goes negative, so the total decrease can't be larger than the total increase. There are therefore at most n fallbacks in the whole run.- The
forloop does O(1) work per character beyond the fallbacks. The total is O(n) + O(n) = O(n).
The same argument works for prefix_function. Its loop runs m − 1 times and increments k at most once per step, so it makes at most m − 1 fallbacks and takes O(m) time. Building the table and then searching costs O(n + m) in total. The only extra memory is the pi array, which is O(m).
Checking it on the naive worst case
The input that pushes naive search to O(n · m) is a text of all a characters and a pattern of the form aa...ab. The code below counts KMP's fallbacks on that input.
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 count_fallbacks(text, pattern):
pi = prefix_function(pattern)
m = len(pattern)
k = 0
fallbacks = 0
for c in text:
while k > 0 and c != pattern[k]:
k = pi[k - 1]
fallbacks += 1
if c == pattern[k]:
k += 1
if k == m:
k = pi[k - 1]
return fallbacks
text = "a" * 10000
pattern = "a" * 99 + "b"
f = count_fallbacks(text, pattern)
print(f) # 9901
print(f <= len(text)) # TrueKMP makes 9,901 fallbacks. Naive search on the same input does about 990,100 character comparisons, because it compares 100 characters at each of its 9,901 shifts.
Exercise
For a pattern of length m = 8, what is the most fallbacks prefix_function can perform in total, and why?
Show answer
At most 7. The loop runs for i = 1 to 7 and increments k at most once per iteration, so k rises by at most 7 in total. Each fallback lowers k by at least 1, and k never goes below 0, so there can be at most 7 fallbacks.
Exercise
After a full match, the search sets k = pi[m - 1]. Does this step break the O(n) bound?
Show answer
No. pi[m - 1] < m, so the reset is one more decrease of k. Decreases are already paid for by earlier increments, so the total of fallbacks plus resets is still at most n.