Skip to content
StackDecode
StringsAnimated

Z Algorithm

For each position, the length of the longest match with the string start.

Time

O(n)

Extra space

O(n)

Use it for

Pattern matching and string periodicity.

How it works

  1. Build the string pattern + "$" + text.
  2. For every position i, Z[i] is the length of the longest substring starting at i that equals a prefix of the whole string.
  3. Keep a window [l, r) of the rightmost match found so far; inside it, Z values can be copied from earlier positions instead of re-compared.
  4. Wherever Z[i] equals the pattern length, the pattern occurs there. O(n + m).

Watch it run

Loading animation…