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
- Build the string pattern + "$" + text.
- For every position i, Z[i] is the length of the longest substring starting at i that equals a prefix of the whole string.
- 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.
- Wherever Z[i] equals the pattern length, the pattern occurs there. O(n + m).
Watch it run
Loading animation…