Skip to main content

Z Algorithm

Definition​

The Z Algorithm is a linear time pattern matching algorithm used to find all occurrences of a pattern in a given text. It preprocesses the pattern to create a Z-array, which stores the longest common prefix between the pattern and every suffix of the pattern. This array is then utilized to efficiently find matches in the text

Practice​

ZAlgorithm(text, pattern):
concat = pattern + "$" + text
Z = [0] * length(concat)
L = 0
R = 0

for i from 1 to length(concat) - 1:
if i > R:
L = R = i
while R < length(concat) and concat[R - L] == concat[R]:
R += 1
Z[i] = R - L
R -= 1
else:
k = i - L
if R - i + 1 > Z[k]:
Z[i] = Z[k]
else:
L = i
while R < length(concat) and concat[R - L] == concat[R]:
R += 1
Z[i] = R - L
R -= 1

matches = []
for i from length(pattern) + 1 to length(concat) - 1:
if Z[i] == length(pattern):
matches.append(i - length(pattern) - 1)

return matches