Практикуйте дискретную математику

Algorithms / Z Function

Least You Need to Know: Z-Function, Prefix Matches, and Pattern Search by Concatenation

The Z-function at position `i` stores the length of the longest substring starting at `i` that matches the whole string prefix. This lets you reason about repeated prefix structure and perform pattern search via concatenation.

The least you need to know

Key notation

Z[i] length of longest prefix match starting at position i
Z-box [L, R] current interval matching the prefix
pattern#text concatenated string for search using a separator

Tiny worked example

  • For string `abacaba`, a position with `Z[i] = 3` means the next three characters match the prefix `aba`.
  • To search for pattern `aba` in text `cabaaba`, build `aba#cabaaba`.
  • Wherever the Z-value equals `3`, the pattern begins there in the text portion.
  • The maintained Z-box avoids restarting comparisons from scratch.

Common mistakes

How to recognize this kind of problem

Start practice