The KMP prefix function
For every prefix of the pattern, find the longest proper prefix that is also its suffix; with this table KMP knows how far to move after a mismatch.
A border of a string is a proper prefix that is also a suffix (for ababa: aba and a). π[q] is the length
of the longest border of P[0..q].
- Time:
O(m) (amortized) - Space:
O(m) - CLRS, section 32.4
- Horowitz–Sahni, chapter 2
The pattern ababaca; π = (0, 0, 1, 2, 3, 0, 1).
def prefix_function(P):# pi[q] = the length of the longest proper prefix of P[0..q] that is also a suffix of it.m = len(P)pi = [0] * mtable = [list(P), pi]k = 0for q in range(1, m):while k > 0 and P[k] != P[q]:k = pi[k - 1]if P[k] == P[q]:k = k + 1pi[q] = kreturn pi
Start
The table is still empty.
Local variables
Orange = changed in this step
Call stack
- prefix_function()line 1
Explanation
The idea
A border of a string is a proper prefix that is also a suffix (for ababa: aba and a). π[q] is the length
of the longest border of P[0..q].
Why it matters
In KMP, when q characters of the pattern have matched and the next one does not, there is no need to start over:
the longest border of the matched part is exactly what is still valid, so we fall back to π[q − 1].
Computing it
The table itself is built with the same idea: if P[k] = P[q] the border grows by one; otherwise fall back to the
next shorter border π[k − 1] and try again.
Cost
k grows at most m times in all and each fall-back shrinks it; so the whole job is O(m) (amortized analysis).
What to watch in the trace
- The
qandkpointers on the pattern; the table pairs each character with itsπ.