Z-Function Prefix Matches
Explore how a shared prefix can reappear inside a string and how a moving window reuses earlier matches.
Free theory articleExplore how a shared prefix can reappear inside a string and how a moving window reuses earlier matches.
Concept & interpretation
The Z-function is a linear-time string matching algorithm that computes the longest common prefix (LCP) between a string and each of its suffixes. For a string s of length n, the Z-array Z[i] stores the length of the LCP of s and s[i..n-1]. By definition, Z[0] = 0 in this specific convention.
Interactive Demonstration
Open the Z-Function interactive experiment. You can use the Text, Step, Finish, and Reset controls.
- Enter the text
abacabaand click Step. - Observe how the algorithm maintains a half-open window
[l, r)representing the rightmost matched prefix segment. - When
ifalls within[l, r), it initializes the current match length fromZ[i - l], avoiding redundant comparisons. - Click Finish to quickly reveal the final array
[0, 0, 1, 0, 3, 0, 1]without viewing intermediate steps. - Invalid characters such as numbers or uppercase letters trigger an error and prevent search continuation.