Chapter 9 · Simulation

KMP Prefix Function and Z Algorithm

← Chapter 9

Prefix function π and Z array (click a column)

Ready.

KMP Prefix Function and Z Algorithm

Two classic linear-time string preprocessing arrays are compared on the same input.

How to use

  • Type a string of up to 40 characters or pick an example, then press Build Arrays (Enter works too).
  • For each index i the table shows the character s[i], the prefix-function value π[i] and the value Z[i]. Strings longer than 20 characters are split into two blocks.
  • Click a column to see what the two values mean: the strips below highlight the matching prefix and block of the string.

Prefix function (π)

π[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it. KMP uses this value to continue matching after a mismatch without moving backwards in the text.

Z array

Z[i] is the length of the longest prefix that matches the substring starting at i. By convention Z[0] is shown as 0. To search for a pattern P in a text T, Z is computed on P + "$" + T: every position with Z[i] = |P| is a match.

Complexity

ArrayTimeMemory
Prefix function πO(n)O(n)
Z arrayO(n)O(n)