Sub topic 9
Proving Linear Running Time
This chapter assumes you already know the code for prefix_function and kmp_search from the earlier chapters. You should also know Big-O notation and be comfortable reading nested loops. The goal here is to prove that KMP runs in O(n + m) time, where n is the text length and m is the pattern length. It also covers where that bound comes from and where it stops applying.
The Apparent Problem: A Loop Inside a Loop
Both functions have the same shape: a for loop over characters, with a while loop inside that falls back through borders.
for i, c in enumerate(text):
while k > 0 and c != pattern[k]:
k = pi[k - 1]
...A quick reading suggests the inner loop can run up to m times for each of the n characters, which would mean O(n · m). That bound is correct, but it is loose. The inner loop can run many times at one position. It cannot do that at every position, because each long run of fallbacks has to be paid for by earlier progress. Turning that idea into a proof is the job of amortized analysis.
The Key Fact: Every Fallback Shrinks k
The whole proof rests on one property of the prefix function:
pi[j] < j + 1 for every index j, which means pi[k − 1] < k for every k ≥ 1.
This holds because pi[k − 1] is the length of the longest proper border of pattern[0..k-1]. A proper border is shorter than the string it belongs to, and that string has length k. So the assignment k = pi[k - 1] always makes k strictly smaller, by at least 1.
Two more facts complete the picture:
- k never goes below 0. The
whilecondition stops atk > 0. - k only increases in one place, the line
k += 1, and that line runs at most once per iteration of theforloop.
The Potential Argument for the Search
Treat k as a counter of stored progress. Every time k goes up by 1, you put one coin in a bank. Every fallback takes at least one coin out. The bank cannot go negative, so the number of withdrawals cannot exceed the number of deposits.
Here is the argument for kmp_search over a text of length n:
- The
forloop runs n times. k += 1runs at most once per iteration, so there are at most n increments in total.- Each fallback, whether from the
whileloop or from the resetk = pi[k - 1]after a match, decreases k by at least 1. - k starts at 0 and never drops below 0. The total decrease therefore cannot exceed the total increase, which is at most n.
- So there are at most n fallbacks in the whole run.
Every iteration of the for loop does a constant amount of work apart from its fallbacks: one or two character comparisons, one if, and possibly appending a match. The total work is therefore
O(n) for the loop body + O(n) for all fallbacks combined = O(n).
In the language of the potential method, let Φ = k. An increment step has actual cost 1 and raises Φ by 1, so its amortized cost is 2. A fallback has actual cost 1 and lowers Φ by at least 1, so its amortized cost is at most 0. Φ starts at 0 and stays nonnegative, so the total actual cost is at most the total amortized cost, which is at most 2n plus a constant per iteration.
The Same Argument for the Prefix Function
prefix_function(p) has exactly the same structure, run over the pattern itself:
| Quantity | Bound | Reason |
|---|---|---|
| Iterations of the `for` loop | m − 1 | i runs from 1 to m − 1 |
| Increments of k | ≤ m − 1 | at most one per iteration |
| Fallbacks (`k = pi[k - 1]`) | ≤ m − 1 | each lowers k by ≥ 1, and k ≥ 0 |
| Total work | O(m) | constant per iteration plus fallbacks |
The fallback reads pi[k - 1], which was already computed because k − 1 < i. The proof needs nothing else about the algorithm.
Adding the two phases gives the full bound:
- Time: O(m) to build
piplus O(n) to scan the text, so O(n + m). - Extra space: O(m) for the
piarray, plus space for the output list of matches.
The text is read once, left to right, and never revisited. That is why KMP works on streams where you cannot seek backward.
Watching the Bound Hold
The instrumented versions below count increments and fallbacks separately and check the inequalities from the proof on inputs designed to stress the inner loop.
def prefix_function_stats(p):
pi = [0] * len(p)
k = 0
increments = fallbacks = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
fallbacks += 1
if p[i] == p[k]:
k += 1
increments += 1
pi[i] = k
return pi, increments, fallbacks
def kmp_search_stats(text, pattern):
m = len(pattern)
pi, _, _ = prefix_function_stats(pattern)
k = 0
increments = fallbacks = 0
matches = []
for i, c in enumerate(text):
while k > 0 and c != pattern[k]:
k = pi[k - 1]
fallbacks += 1
if c == pattern[k]:
k += 1
increments += 1
if k == m:
matches.append(i - m + 1)
k = pi[k - 1]
fallbacks += 1
return matches, increments, fallbacks
cases = [
("aaaac" * 4, "aaaab"), # long climbs, then a full collapse
("a" * 30, "aaaa"), # a match at every position
("ab" * 15, "aba"), # overlapping matches
("abacabadabacaba" * 3, "abacabab"),
]
for text, pattern in cases:
pi, p_inc, p_fb = prefix_function_stats(pattern)
matches, inc, fb = kmp_search_stats(text, pattern)
n, m = len(text), len(pattern)
assert p_fb <= p_inc <= m - 1
assert fb <= inc <= n
print(f"n={n:3} m={m} increments={inc:3} fallbacks={fb:3} "
f"matches={len(matches)}")Every assertion passes. In each row the fallback count stays at or below the increment count, and the increment count stays at or below n.
A Trace of the Worst Single Step
Take pattern "aaaab", whose prefix function is [0, 1, 2, 3, 0], and text "aaaacaaaac". Here is k after each text character:
| i | char | k before | fallbacks at this step | k after |
|---|---|---|---|---|
| 0 | a | 0 | 0 | 1 |
| 1 | a | 1 | 0 | 2 |
| 2 | a | 2 | 0 | 3 |
| 3 | a | 3 | 0 | 4 |
| 4 | c | 4 | 4 (4→3→2→1→0) | 0 |
| 5 | a | 0 | 0 | 1 |
| 6 | a | 1 | 0 | 2 |
| 7 | a | 2 | 0 | 3 |
| 8 | a | 3 | 0 | 4 |
| 9 | c | 4 | 4 | 0 |
The step at i = 4 is expensive: four fallbacks for one character. It was only possible because the four steps before it each raised k by 1. Over the whole text there are 8 increments and 8 fallbacks, within the bound.
An Alternative View: The Window Never Moves Backward
The same proof can be stated in terms of the naive algorithm. At any moment, KMP is effectively testing the pattern aligned to start at text position s = i − k, where i is the index of the next character to read. Look at how s changes:
- An increment raises both i and k by 1, so s stays the same.
- A fallback lowers k and leaves i alone, so s increases by at least 1.
- A mismatch with k = 0 raises i, so s increases by 1.
The alignment s never decreases and never exceeds n, so fallbacks can happen at most n times. Naive search resets to every alignment and re-reads characters. KMP slides the alignment forward and never re-reads the text. Both views count the same events.
Amortized Is Not Per-Character
The bound applies to the total, not to each character. In the trace above one character caused m − 1 fallbacks. For a pattern like "a" * (m - 1) + "b", a single text character can cost Θ(m) work, even though the whole run is still O(n + m).
This matters in a few situations:
- Real-time systems that must handle each incoming byte within a fixed deadline, such as network packet inspection, care about the worst single step. The KMP automaton from a later chapter gives O(1) work per character, at the cost of O(m · σ) space for an alphabet of size σ.
- Interactive or streaming code that measures latency per event will see occasional spikes, even though throughput is linear.
Implementation Mistakes That Break the Bound
The proof only covers code that keeps its two assumptions: k rises by at most 1 per step, and every fallback strictly lowers k. These changes break the linear bound or hide extra cost:
| Mistake | Effect |
|---|---|
| Moving `i` backward after a mismatch to retry from the next start | Turns KMP back into naive search, O(n · m) |
| Checking a candidate with `text[i - m + 1:i + 1] == pattern` | Each slice comparison costs O(m), and the hidden cost is easy to miss |
| Building `pi` by comparing every prefix against every suffix | O(m²) or worse preprocessing |
| Writing `k = pi[k]` instead of `k = pi[k - 1]` | k may not decrease, which can cause wrong answers or an infinite loop |
| Recomputing `prefix_function(pattern)` inside a loop over many texts | Correct, but pays O(m) again each time. Compute it once and reuse it |
Resetting k = 0 after a match, instead of k = pi[m - 1], is still linear. It just misses overlapping matches, which the edge-cases chapter covers.
Exercise
Show that computing the prefix function of a pattern of length m performs at most m − 1 fallbacks in total, and explain which property of pi the argument depends on.
Show answer
The for loop runs for i = 1 to m − 1 and executes k += 1 at most once per iteration, so k increases by at most m − 1 overall. Each fallback k = pi[k − 1] makes k strictly smaller because pi[k − 1] is the length of a proper border of a string of length k, so pi[k − 1] < k. Since k starts at 0 and never becomes negative, the total decrease, and therefore the number of fallbacks, is at most the total increase, m − 1.
Exercise
Run KMP with pattern "aaaab" on the text "aaaac" repeated r times. How many increments and fallbacks happen in total, and what is the largest number of fallbacks caused by a single character?
Show answer
Each block of five characters raises k from 0 to 4 with four increments, then the 'c' causes four fallbacks (4→3→2→1→0), and the final comparison at k = 0 fails without a fallback. In total there are 4r increments and 4r fallbacks for a text of length n = 5r, which is within the n bound. The largest single-character cost is 4 fallbacks, which is m − 1.
Exercise
A colleague replaces the fallback line with k = k - 1 ("just back off one character") and argues the running time is still linear because k still decreases. Is the running time still linear? Is the algorithm still correct?
Show answer
The running time is still O(n + m), because each fallback still lowers k by at least 1 and the same counting argument applies. The algorithm is no longer correct. k − 1 is not necessarily the length of a border of the matched prefix, so after the change k may not describe a real prefix of the pattern ending at the current position. The search can then report false matches or miss real ones. The linear bound comes from the fallback shrinking k, and correctness comes from it landing on a border. KMP needs both.