Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

The Prefix Function & Z-Function in Depth

Failure links, string periods and matching automata.

The prefix function packs everything a string knows about its own overlaps into one array. Read it right and it lists every period of every prefix, builds a matching automaton, and counts the occurrences of every prefix, all in linear time. Behind it sits a 1965 theorem about periodic functions that tells you when two periods force a third.

What you’ll learn

  • Prove that periods and borders are dual (qq is a period iff n−qn - q is a border length) and that the chain π[n−1],π[π[n−1]−1],…\pi[n-1], \pi[\pi[n-1]-1], \dots lists every border.
  • Prove the periodicity lemma of Fine and Wilf, and use it to show that a power's shortest root has length n−π[n−1]n - \pi[n-1].
  • Prove linear bounds for computing π\pi and ZZ with potential functions, and convert ZZ to π\pi.
  • Build the KMP automaton, count the occurrences of every prefix, and state the lower bounds and the constant-space, real-time and streaming variants of matching.

Borders and periods

DerivationProof
  1. q is a period  ⟺  s[0..n−q)=s[q..n)q \text{ is a period} \iff s[0..n-q) = s[q..n)

    (a) Duality. The condition s[i]=s[i+q]s[i] = s[i+q] for all valid ii says, position by position, that the prefix of length n−qn - q equals the suffix of length n−qn - q:

  2. v is a border of s, ∣v∣<∣u∣ ⟹ v is a border of uv \text{ is a border of } s,\ \abs v < \abs u \ \Longrightarrow\ v \text{ is a border of } u

    Borders nest. Let uu and vv be borders of ss with ∣v∣<∣u∣\abs v < \abs u. Then vv is a prefix of ss shorter than the prefix uu, so a prefix of uu; likewise vv is a suffix of uu. Hence:

  3. Borders⁡(s)={∣u1∣}∪Borders⁡(u1)\operatorname{Borders}(s) = \{\abs{u_1}\} \cup \operatorname{Borders}(u_1)

    (b) The chain is complete. The longest border of ss is u1=s[0..π[n−1])u_1 = s[0..\pi[n-1]). Every shorter border of ss is a border of u1u_1, and conversely every border of u1u_1 is a border of ss. So the next border is the longest border of u1u_1, of length π[∣u1∣−1]\pi[\abs{u_1} - 1], and induction finishes the proof:

Check your understanding

The prefix function of s=aabaabaas = \texttt{aabaabaa} is [0,1,0,1,2,3,4,5][0, 1, 0, 1, 2, 3, 4, 5]. What are all the periods of ss?

  1. 3 only
  2. 3, 6, 7 and 8
  3. 3 and 8
  4. 5, 2 and 1
Show the answer

B. 3, 6, 7 and 8

The border chain is π[7]=5\pi[7] = 5, then π[4]=2\pi[4] = 2, then π[1]=1\pi[1] = 1, then 0: the borders aabaa\texttt{aabaa}, aa\texttt{aa} and a\texttt{a}. The periods are 8−5=38 - 5 = 3, 8−2=68 - 2 = 6, 8−1=78 - 1 = 7, and the trivial period 8.

The periodicity lemma

DerivationProof of the weak form, with |s| ≥ p + q
  1. goal: s[i]=s[i+p−q](0≤i<n−p+q)\text{goal: } s[i] = s[i + p - q] \quad (0 \le i < n - p + q)

    Setup. Let p>qp > q be periods and n=∣s∣≥p+qn = \abs s \ge p + q. We show that p−qp - q is a period: s[i]=s[i+p−q]s[i] = s[i + p - q] for every 0≤i<n−(p−q)0 \le i < n - (p - q). Two cases cover all ii.

  2. s[i]=s[i+p]=s[i+p−q]s[i] = s[i + p] = s[i + p - q]

    Case i+p<ni + p < n. Step forward by pp, then back by qq (the second step uses period qq at index i+p−qi + p - q, valid because i+p<ni + p < n):

  3. s[i]=s[i−q]=s[i−q+p]s[i] = s[i - q] = s[i - q + p]

    Case i+p≥ni + p \ge n. Then i≥n−p≥qi \ge n - p \ge q, so step back by qq, then forward by pp (valid because i−q+p<ni - q + p < n):

  4. {p,q}→{p−q,q}→⋯→{gcd⁡(p,q),gcd⁡(p,q)}\{p, q\} \to \{p - q, q\} \to \cdots \to \{\gcd(p,q), \gcd(p,q)\}

    Euclid. So p−qp - q is a period, and n≥(p−q)+qn \ge (p - q) + q still holds. Repeat the subtraction, as in the subtractive form of Euclid's algorithm, until the two periods become equal; they end at the gcd:

Check your understanding

A string of length 9 has periods 4 and 6. What follows?

  1. Nothing more: the lemma needs length at least 4+6=104 + 6 = 10
  2. It has period 1
  3. It has period 10
  4. It has period 2
Show the answer

D. It has period 2

The sharp form needs only 9≥4+6−gcd⁡(4,6)=89 \ge 4 + 6 - \gcd(4,6) = 8, so gcd⁡(4,6)=2\gcd(4, 6) = 2 is a period. At length 7 it can fail: aaabaaa\texttt{aaabaaa} has periods 4 and 6 but not 2.

Linear time, and π versus Z

Both arrays come from algorithms whose inner loops look quadratic. A potential function makes the amortized argument exact.

DerivationPotential arguments for π and Z
  1. ci=fi+1,ki≤ki−1−fi+1c_i = f_i + 1, \qquad k_i \le k_{i-1} - f_i + 1

    The prefix function. At step ii, let fif_i be the number of fallbacks; the step makes ci=fi+1c_i = f_i + 1 comparisons. Each fallback lowers the current border length kk by at least 1, and the step raises it by at most 1:

  2. ∑i=1m−1ci ≤ 2(m−1)−km−1+k0 ≤ 2(m−1)\sum_{i=1}^{m-1} c_i \ \le\ 2(m-1) - k_{m-1} + k_0 \ \le\ 2(m-1)

    Sum. With Φ=k\Phi = k, the amortized cost ci+(ki−ki−1)c_i + (k_i - k_{i-1}) is at most 2. Summing over i=1,…,m−1i = 1, \dots, m-1, with k0=0k_0 = 0 and km−1≥0k_{m-1} \ge 0:

  3. #comparisons ≤ n⏟successes+n⏟failures=2n\#\text{comparisons} \ \le\ \underbrace{n}_{\text{successes}} + \underbrace{n}_{\text{failures}} = 2n

    The Z-function. Take Φ=r\Phi = r, the right end of the box. A comparison beyond the box that succeeds raises rr by one when the box is updated, and r≤nr \le n never decreases; each ii adds at most one failed comparison:

The two arrays describe the same self-overlaps from opposite ends. Z[i]=LZ[i] = L says that the prefixes of lengths 1,…,L1, \dots, L occur starting at ii, so they end at positions i,…,i+L−1i, \dots, i + L - 1 and are borders of the prefixes ending there. Conversely, Z[i]Z[i] is the largest LL that appears on the border chain at position i+L−1i + L - 1, so π\pi determines ZZ as well.

python
def z_to_pi(z):
    n = len(z)
    pi = [0] * n
    for i in range(1, n):
        for j in range(z[i] - 1, -1, -1):  # prefix of length j + 1 ends at i + j
            if pi[i + j] > 0:
                break                      # set by a smaller i: a longer border
            pi[i + j] = j + 1
    return pi

Linear time: every entry is set once, and each ii breaks at most once. A smaller start ii gives a longer border at the same end position, so the first value written is the right one, and every entry below a set one is already set.

Automata and counting

python
def kmp_automaton(p, alphabet):
    pi, m = prefix_function(p), len(p)
    delta = [dict() for _ in range(m + 1)]
    for q in range(m + 1):
        for c in alphabet:
            if q < m and p[q] == c:
                delta[q][c] = q + 1
            elif q == 0:
                delta[q][c] = 0
            else:
                delta[q][c] = delta[pi[q - 1]][c]   # already computed: pi[q-1] < q
    return delta

O(m∣Σ∣)O(m\abs\Sigma) time and space. Since π[q−1]<q\pi[q-1] < q, each missing transition copies one computed earlier, with no fallback loop at all.

The automaton spends exactly one table lookup per text character: it runs in real time. Plain KMP has the same total cost, at most 2n2n comparisons, but can spend several of them on a single character. Knuth showed that this delay is O(log⁡m)O(\log m), bounded by about log⁡φm\log_\varphi m with φ\varphi the golden ratio, and Fibonacci strings come close: a Fibonacci pattern of length 377 can force 12 comparisons on one character. Galil (1981) made matching real-time without an alphabet-sized table.

The prefix function also counts. Each position ii is the end of an occurrence of the prefix of length π[i]\pi[i], and of every shorter border on its chain. Count the values of π\pi, push the counts down the chains in decreasing order of length, and add each prefix's own occurrence at position 0:

python
def prefix_occurrences(s):
    n, pi = len(s), prefix_function(s)
    cnt = [0] * (n + 1)
    for i in range(n):
        cnt[pi[i]] += 1                # the longest border ending at i
    for L in range(n, 0, -1):
        cnt[pi[L - 1]] += cnt[L]       # its shorter borders end there too
    for L in range(n + 1):
        cnt[L] += 1                    # the prefix itself, at position 0
    return cnt[1:]                     # occurrences of s[:1], s[:2], ..., s[:n]

For abacaba\texttt{abacaba} this returns [4,2,2,1,1,1,1][4, 2, 2, 1, 1, 1, 1]: a\texttt{a} occurs four times, ab\texttt{ab} and aba\texttt{aba} twice each. Running the same trie-based idea for many patterns at once gives Aho–Corasick, whose failure links are the prefix function of a whole dictionary.

Lower bounds and the frontier

Linear time is the floor; the frontier is in the other resources.

  • Constant extra space. KMP stores π\pi, Θ(m)\Theta(m) words. Galil and Seiferas (1983) matched in linear time with O(1)O(1) extra space, and the Two-Way algorithm of Crochemore and Perrin (1991) does it simply, by splitting the pattern at a critical factorization, where the local period equals the global one. Two-Way is what glibc's strstr uses for long needles and what CPython falls back to since 3.10.
  • Streaming. If the text arrives one character at a time and even the pattern cannot be stored, Porat and Porat (2009) matched with O(log⁡m)O(\log m) words, combining the periodicity of prefixes with fingerprints, and showed Ω(log⁡m)\Omega(\log m) space is needed; Breslauer and Galil (2014) made it real-time. These algorithms are randomized, with one-sided errors.

Key takeaways

  • Periods and borders are dual: qq is a period of ss exactly when ss has a border of length n−qn - q, and the chain π[n−1],π[π[n−1]−1],…\pi[n-1], \pi[\pi[n-1]-1], \dots lists every border, hence every period.
  • Fine and Wilf: periods pp and qq with n≥p+q−gcd⁡(p,q)n \ge p + q - \gcd(p,q) force period gcd⁡(p,q)\gcd(p,q), and the bound is sharp. Consequently a string is a power exactly when n−π[n−1]n - \pi[n-1] is a proper divisor of nn.
  • π\pi and ZZ are computed in linear time by potential arguments (Φ=k\Phi = k and Φ=r\Phi = r), and each determines the other; ZZ converts to π\pi in O(n)O(n).
  • The KMP automaton spends exactly one transition per text character after O(m∣Σ∣)O(m\abs\Sigma) preprocessing, and prefix-function counts give the number of occurrences of every prefix in O(n)O(n).
  • Every matcher must read n−m+1n - m + 1 text characters in the worst case (Rivest); Two-Way matches in linear time with O(1)O(1) extra space, and fingerprints give streaming matching in O(log⁡m)O(\log m) words.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A string ss of length 12 has π[11]=8\pi[11] = 8. What is ss?

  1. A primitive string: it is not a power of a shorter string
  2. u2u^2 for a string uu of length 6
  3. u3/2u^{3/2} for a string uu of length 8
  4. u3u^3 for a string uu of length 4
Show the answer

D. u3u^3 for a string uu of length 4

The shortest period is d=12−8=4d = 12 - 8 = 4, which divides 12, so s=s[0..4)3s = s[0..4)^3, as in abcdabcdabcd\texttt{abcdabcdabcd}. It cannot also have period 6: periods 4 and 6 in a string of length 12≥4+6−212 \ge 4 + 6 - 2 would force period 2 by Fine–Wilf, contradicting that 4 is the shortest period.

Question 2

Which string shows that the bound p+q−gcd⁡(p,q)p + q - \gcd(p, q) in the Fine–Wilf lemma cannot be lowered for p=3p = 3, q=5q = 5?

  1. aaaaaa\texttt{aaaaaa}
  2. abcabc\texttt{abcabc}
  3. abaab\texttt{abaab}
  4. abaaba\texttt{abaaba}
Show the answer

D. abaaba\texttt{abaaba}

abaaba\texttt{abaaba} has length 6=3+5−1−16 = 3 + 5 - 1 - 1, period 3 (aba aba\texttt{aba}\,\texttt{aba}) and period 5 (its first and last characters agree), but not period 1. One character longer, the lemma would force period 1.

Question 3

Plain KMP and the KMP automaton both match in O(n+m)O(n + m) total time. What does the automaton add?

  1. Exactly one transition per text character, so constant work per character in the worst case, paid for with an O(m∣Σ∣)O(m\abs\Sigma) table
  2. Fewer total comparisons on every input
  3. The ability to match several patterns at once
  4. Independence from the alphabet size
Show the answer

A. Exactly one transition per text character, so constant work per character in the worst case, paid for with an O(m∣Σ∣)O(m\abs\Sigma) table

KMP's fallback loop can spend up to about log⁡φm\log_\varphi m comparisons on a single character, although the total stays below 2n2n. The automaton precomputes the result of every fallback chain for every character, so each text character costs one lookup: real time.

Question 4

Boyer–Moore often skips most of the text. Can any algorithm guarantee examining fewer than n−m+1n - m + 1 text characters on every input?

  1. Yes, Boyer–Moore with Galil's rule does
  2. Yes, with a large enough alphabet
  3. No: Rivest proved that some inputs force at least n−m+1n - m + 1 examined characters
  4. Only with randomization
Show the answer

C. No: Rivest proved that some inputs force at least n−m+1n - m + 1 examined characters

An adversary can hide an occurrence in any unexamined window, so in the worst case every algorithm reads at least n−m+1n - m + 1 characters (Rivest, 1977). Sublinear behavior is an average-case or typical-input property.

Further reading

  • D. E. Knuth, J. H. Morris & V. R. Pratt, "Fast pattern matching in strings," SIAM Journal on Computing 6(2) (1977), 323–350.
  • N. J. Fine & H. S. Wilf, "Uniqueness theorems for periodic functions," Proceedings of the American Mathematical Society 16 (1965), 109–114.
  • R. L. Rivest, "On the worst-case behavior of string-searching algorithms," SIAM Journal on Computing 6(4) (1977), 669–674.
  • M. Crochemore & D. Perrin, "Two-way string-matching," Journal of the ACM (1991).
  • D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997).