Skip to content
Efficient

Z Algorithm

Pattern matching using the Z-array technique.

Time Complexity
O(N + M)
Space Complexity
O(N)

Interactive Visualization

Playback Speed
Execution State
STEP 1 / 42
Concatenated (P + $ + T)
A
0
B
1
A
2
$
3
A
4
B
5
A
6
B
7
D
8
A
9
B
10
A
11
C
12
Z-Array (LCP with Prefix)
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
0
10
0
11
0
12
Process Description

Initializing Z-array. Z[0] is usually not defined or 0.

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

  • 1
    Creating the string P + separator + T.
  • 2
    Maintaining a 'Z-box' [L, R] which is the rightmost matched interval.
  • 3
    Using values inside the Z-box to compute new Z-values in O(1).
  • 4
    Extending 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.