Efficient
Z Algorithm
Pattern matching using the Z-array technique.
Time Complexity
O(N + M)
Space Complexity
O(N)
Interactive Visualization
Technical Guide
The Z-Algorithm computes an array Z where Z[i] is the length of the longest common prefix between the string S and the suffix of S starting at i. By concatenating the pattern and the text (P + $ + T), we can find all matches by looking for Z[i] values equal to the pattern length. It is as efficient as KMP but often considered more intuitive to visualize.
Logical Phases
- 1Creating the string P + separator + T.
- 2Maintaining a 'Z-box' [L, R] which is the rightmost matched interval.
- 3Using values inside the Z-box to compute new Z-values in O(1).
- 4Extending the Z-box linearly when i is outside the current range.
Implementation
if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]);Expert Pitfalls
Using a separator character that actually appears in the text or pattern.