We are asked: "Write a program that implements the Z-algorithm for pattern matching."
Interpretation: We need to write a program (likely in a language, but not specified) that implements the Z-algorithm for pattern matching. This is a typical algorithm used for pattern matching in strings. The Z-algorithm computes an array Z where Z[i] is the length of the longest substring starting from position i that matches the prefix of the string. For pattern matching, we can concatenate pattern and text with a separator, compute Z, and then occurrences correspond to Z values equal to pattern length.
We should produce a program that reads input: pattern and text? Or just a function? The prompt is vague. Typically, in coding challenges, we need to write a function that given two strings, returns indices of matches. But the prompt says "Write a program that implements the Z-algorithm for pattern matching." So we can assume we need to provide a complete runnable program that takes input (maybe from standard input) and outputs positions where pattern occurs in text.
Let's decide: I'll write in Python, as it's common. The program will read two lines: first line pattern, second line text. It will then output the indices (0-based or 1-based?) Usually pattern matching indices are 0-based. We'll output each index on a new line where pattern matches in text.
But let's think: The Z-algorithm is usually implemented as a function to compute Z-array. For pattern matching, we create S = pattern + '$' + text, compute Z, then for i > len(pattern), if Z[i] == len(pattern), then pattern occurs at i - len(pattern) - 1 (0-based in text). That's typical.
We need to ensure that the separator is not present in pattern or text; we can use a character that is not in the alphabet, like a special symbol. But simpler: just use a character like '#' or '$' assuming it's not part of the strings. But we cannot guarantee that. Better approach: Use a sentinel that is not in the ASCII range; but in Python, we can use a character that is not likely to appear. Or we can use a tuple of indices, but it's simpler to just use a separator and hope it's not present. Alternatively, we can modify the algorithm to not require a separator by computing Z only for the concatenated string with a delimiter that we are sure is unique by using a character not in the strings; but we could also use two strings and compute Z differently. However, typical implementations use a separator.
Given the problem statement is just to implement Z-algorithm, we can implement a function compute_z(s) that returns Z array. Then in main, read pattern and text, compute Z on pattern + "$" + text, then output indices.
Let's also note that we need to handle large inputs efficiently. Z-algorithm runs in O(n).
Edge cases: pattern longer than text -> no matches; pattern empty? Possibly not.
Now, produce the program. We'll include explanation in comments.
We'll output 0-based indices.
Let's write the code.
We need to define compute_z(s):
code
def compute_z(s):
n = len(s)
z = [0] * n
l, r = 0, 0
for i in range(1, n):
if i > r:
l = r = i
while r < n and s[r - l] == s[r]:
r += 1
z[i] = r - l
r -= 1
else:
k = i - l
if z[k] < r - i + 1:
z[i] = z[k]
else:
l = i
while r < n and s[r - l] == s[r]:
r += 1
z[i] = r - l
r -= 1
return z
That's the classic algorithm.
Now main:
code
import sys
def main():
data = sys.stdin.read().splitlines()
if not data:
return
pattern = data[0].rstrip('\n')
text = data[1].rstrip('\n') if len(data) > 1 else ''
# handle empty pattern: maybe match at every position? But typical pattern matching says empty pattern matches everywhere? Probably not required.
# We'll assume pattern non-empty.
if pattern == "":
# match at all indices? Not defined; just return.
return
s = pattern + "$" + text
z = compute_z(s)
p_len = len(pattern)
res = []
for i in range(p_len + 1, len(s)):
if z[i] == p_len:
# index in text: i - (p_len + 1)
res.append(i - p_len - 1)
# Output results
for idx in res:
print(idx)
if __name__ == "__main__":
main()
But the prompt: "Write a program that implements the Z-algorithm for pattern matching." Possibly they expect to just provide the algorithm, not necessarily a full I/O program. However, "program" suggests a runnable code. So we'll provide a full program.
Maybe we should also output the Z-array? No, pattern matching.
We'll include docstring/comments.
We'll also consider using a separator that is guaranteed not in strings: we can use a character that is not in the union of characters; but simpler to use a string that is not likely. In many competitive programming tasks, they use '#' or '$' and it's fine.
Alternatively, we can avoid separator by building Z for concatenated string without delimiter but then we need to ensure that we don't get matches that cross the boundary; using delimiter prevents that because the delimiter is not part of pattern/text.
Given the problem is generic, we can just use a character not in the strings. To be safe, we could choose a character that is not in the ASCII printable range, e.g., '\0' (null). But Python strings can contain null. However, it's unlikely. We'll use '$'.
Better: we can compute Z only for the part after pattern by constructing a new string = pattern + text and compute Z for that, but then we must restrict to positions after pattern. Actually, the standard approach uses a separator to avoid the pattern matching itself across the boundary. But we can also compute Z for pattern + text and then only consider i >= len(pattern) and ensure that Z[i] >= len(pattern) but also that the match doesn't go beyond the pattern length? Actually, if we compute Z on S = pattern + text, then for i >= len(pattern), the longest prefix match could be longer than pattern length because text might continue the prefix; but we only want matches exactly equal to pattern length? Actually, we want to find occurrences of pattern in text; if Z[i] >= len(pattern), that means the substring starting at i matches the prefix (which is pattern) for at least len(pattern) characters. Since the prefix is pattern, that's exactly a match. However, the prefix includes the entire pattern, so if Z[i] >= len(pattern), it's a match. The problem is that when i < len(pattern), we might get matches from overlapping within pattern, but we ignore those. So we don't strictly need a separator; we can just compute Z for S = pattern + text, then for i from len(pattern) to len(S)-1, if Z[i] >= len(pattern) then pattern occurs at i - len(pattern). Wait careful: if S = pattern + text, then indices: 0..p-1 pattern, p..p+t-1 text. For i >= p, Z[i] is the length of match with prefix (pattern). If Z[i] >= p, then starting at i, the substring matches pattern fully. That's a match. So we don't need a separator. However, there is a subtlety: If pattern appears at the beginning of text, and text starts with pattern, then at index i = p, Z[p] will be at least p? Actually, if text begins with pattern, then S[p:] starts with pattern, so Z[p] will be the length of match with prefix. It could be exactly p if the text doesn't continue with more matching characters beyond p? But if text has pattern and then more characters that also match the prefix? That's possible if pattern has overlap with itself; for example pattern = "aaa", text = "aaaa". Then S = "aaa" + "aaaa" = "aaaaaa". At i = p = 3, we have substring "aaa" (positions 3,4,5?) Actually S[3:] = "aaa"? Let's compute: S = "aaa"+"aaaa" = "aaaaaa". indices: 0 a,1 a,2 a,3 a,4 a,5 a. For i=3, we compare S[3:] = "aaa" (positions 3,4,5) to prefix "aaa" (positions 0,1,2). They match 3 characters. So Z[3]=3 which equals p. So it's a match. But what about i=4? S[4:]="aa" matches prefix "aa" so Z[4]=2, not a full match. So we only need Z[i] >= p. However, we must ensure that Z[i] does not exceed p because we only care about full pattern match; but if Z[i] > p, that would mean the substring starting at i matches the prefix for more than p characters, but since prefix is only p characters, that can't happen because the prefix length is p, so the maximum Z[i] can be is p. Actually, Z[i] is defined as the longest substring starting at i that matches the prefix. The prefix is only length p, so Z[i] <= p. So Z[i] can be at most p. So if Z[i] == p, it's a match. So we don't need separator. But wait: If we have S = pattern + text, then the prefix is pattern, length p. So Z[i] can be at most p because you can't compare beyond the prefix length; you stop when you reach end of string or mismatch. So yes, Z[i] <= p. So condition Z[i] == p is sufficient. So we can avoid separator. That's simpler and avoids delimiter issues. But the classical Z algorithm for pattern matching uses a separator to avoid overlapping matches that might be counted incorrectly? Actually, I recall the typical pattern matching with Z uses concatenation with a separator to ensure that the Z values for the text part are not influenced by the pattern part overlapping into the text part? Let's test: Without separator, if pattern = "aba", text = "ababa". Then S = "abaababa". Compute Z. Let's manually compute: S = "a b a a b a b a" indices:0-7. p=3. We want to find occurrences in text. text starts at index 3. At i=3, S[3:] = "ababa"? Actually S[3] = 'a', S[4]='b', S[5]='a', S[6]='b', S[7]='a' => "ababa". Compare with prefix "aba": first three characters: 'a' matches 'a', 'b' matches 'b', 'a' matches 'a', so Z[3]=3. So we get match at index 3, which corresponds to text position 0? Since text starts at index 3, i - p = 0, correct. Next, i=4: S[4:]="baba". Compare with prefix: 'b' vs 'a' mismatch, Z[4]=0. i=5: S[5:]="aba". Compare with prefix: 'a' vs 'a', 'b' vs 'b', 'a' vs 'a', matches all three, but note there are only three characters left? Actually S length is 8, so from index 5 we have positions 5,6,7: 'a','b','a' -> three characters, so Z[5]=3. That's a match at i=5, which corresponds to text position 2? i-p=5-3=2. Indeed, text has "aba" at position 2 (0-based). So it correctly finds overlapping occurrences. So no separator needed.
But why do some implementations use a separator? Possibly to avoid the case where pattern appears as part of the prefix matching that includes characters from pattern itself? Actually, the Z array for positions within pattern (i < p) are also computed, but we ignore those. Using a separator ensures that the prefix is exactly pattern and that the text part does not get confused with pattern part, but it's not necessary. However, there is a nuance: If pattern has a suffix that matches its prefix, then when computing Z for indices in the text part, the algorithm might use the Z-box from the pattern part to speed up. That's fine. The algorithm works regardless. So we can implement without separator.
But many educational resources use a separator to avoid the pattern and text overlapping in the concatenated string; but it's not required for correctness. I'll use separator for clarity, but either is fine.
I think I'll implement with separator for robustness, though we must ensure the separator is not in the strings. But we can simply use a character that is not in the strings by checking; but that's overkill. Since the problem is just to demonstrate Z-algorithm, we can use '$' and assume it's not present.
Alternatively, we could implement without separator to avoid the issue. Let's do without separator: S = pattern + text. Then Z[i] for i from len(pattern) to len(S)-1; if Z[i] == len(pattern), output i - len(pattern). That's simpler and no delimiter.
Let's adopt that.
Edge cases: If pattern is empty, we might output all indices? Usually pattern matching for empty pattern is not defined, but we could handle by printing nothing or all indices. I'll just handle if pattern empty: print nothing.
Also if text empty: no matches.
Implementation details: The Z algorithm's loop starts from i=1. We'll implement as described.
Let's write final code:
code
import sys
def z_array(s):
n = len(s)
z = [0]*n
l, r = 0, 0
for i in range(1, n):
if i <= r:
k = i - l
if z[k] < r - i + 1:
z[i] = z[k]
else:
l = i
while r < n and s[r] == s[r - l]:
r += 1
z[i] = r - l
r -= 1
else:
l = i
r = i
while r < n and s[r] == s[r - l]:
r += 1
z[i] = r - l
r -= 1
return z
def main():
data = sys.stdin.read().splitlines()
if len(data) < 2:
return
pat = data[0].rstrip('\n')
txt = data[1].rstrip('\n')
if not pat:
# no pattern, no matches
return
s = pat + txt
z = z_array(s)
p_len = len(pat)
matches = []
for i in range(p_len, len(s)):
if z[i] == p_len:
matches.append(i - p_len)
for pos in matches:
print(pos)
if __name__ == "__main__":
main()
That should work.
But note: The condition for using the previously computed Z-box is "if i <= r" not "if i > r". In my code I used "if i <= r". In many implementations, they write "if i > r" then compute from scratch, else use the box. So I'll adjust: The code I wrote earlier used "if i > r" then ... else ... I'll correct.
Standard implementation:
code
def compute_z(s):
n = len(s)
z = [0]*n
l = r = 0
for i in range(1, n):
if i <= r:
k = i - l
if z[k] < r - i + 1:
z[i] = z[k]
else:
l = i
while r < n and s[r] == s[r - l]:
r += 1
z[i] = r - l
r -= 1
else:
l = i
r = i
while r < n and s[r] == s[r - l]:
r += 1
z[i] = r - l
r -= 1
return z
Yes.
Now test with sample:
pattern = "aba", text = "ababa". Output should be 0 and 2.
Let's simulate quickly:
s = "abaababa". len = 8. Compute Z:
i=1: i>r (r=0) => l=1, r=1: while r<8 and s[1]==s[0]? s[1]='b', s[0]='a' -> false, so z[1]=0, r stays 1? Actually after while, r=1, then z[1]=r-l=0, r-- => r=0. So z[1]=0.
i=2: i>r (0) => l=2,r=2: s[2]='a' vs s[0]='a' -> match, r=3; s[3]='a' vs s[1]='b'? mismatch, stop. z[2]=1, r=2 after decrement? Actually after while, r=3, then z[2]=1, r-- => r=2.
i=3: i<=r? r=2, i=3 >2 => else? Actually i=3 > r=2, so else branch: l=3,r=3: s[3]='a' vs s[0]='a' -> match, r=4; s[4]='b' vs s[1]='b'? match, r=5; s[5]='a' vs s[2]='a'? match, r=6; s[6]='b' vs s[3]='a'? mismatch, stop. So z[3]=3 (r-l=6-3=3), r=5 after decrement.
i=4: i=4 <= r=5? Yes. k= i-l = 4-3=1. z[1]=0, r-i+1 = 5-4+1=2. Since 0<2, so z[4]=z[1]=0.
i=5: i=5 <= r=5? Yes, i==r. k=5-3=2, z[2]=1, r-i+1=5-5+1=1, since z[2]>=1? Actually 1 < 1? No, it's equal, so the condition is if z[k] < r - i + 1: then assign else expand. Since 1 is not < 1, we go to else. Then l=i=5, while r < n and s[r]==s[r-l]: r=5 initially? Wait r is currently 5. We'll set l=5, then we need to expand from current r? In the else block, we set l=i, then while r < n and s[r] == s[r-l]: r+=1. But careful: In this case, r is 5, l=5, r-l=0, compare s[5] to s[0]? But we should continue from where we left? The algorithm typically sets l=i, and then expands from current r (which is at least i). Actually standard implementation: if i <= r, then k = i-l; if z[k] < r - i + 1: z[i] = z[k]; else: l = i; while r < n and s[r] == s[r - l]: r += 1; z[i] = r - l; r -= 1. In this case, we already have r = 5, which is the right boundary of the current Z-box. Since we are in the else branch, we need to expand from r onward. But note that we might have already matched some characters up to r. So we set l=i, then we try to extend r while s[r] == s[r-l]. Since currently r = 5, we check s[5] vs s[0]? s[5]='a', s[0]='a' -> match, so r becomes 6. Then check s[6] vs s[1]: s[6]='b', s[1]='b' -> match, r=7. Check s[7] vs s[2]: s[7]='a', s[2]='a' -> match, r=8 (n=8, so stop because r == n). Then z[5] = r - l = 8-5=3. r-- => r=7. So z[5]=3.
i=7: i=7 <= r=7? Yes. k=7-5=2, z[2]=1, r-i+1=7-7+1=1, 1 not <1 => else. l=7, while r<n? r=7, check s[7] vs s[0]: s[7]='a', s[0]='a' -> match, r=8. Then z[7]=1, r-- => r=7? Actually after while, r=8, then z[7]=1, r-- => r=7. So z[7]=1.
Thus Z array: [0,0,1,3,0,3,0,1]? Actually index 0 is not used; Z[0] is typically defined as n, but we set it to 0. In our algorithm we start from i=1, leaving Z[0]=0. But for pattern matching we don't use Z[0]. However, sometimes Z[0] is defined as n; but it's not needed. So for i from p=3 onward: i=3 Z=3 -> match; i=4 Z=0; i=5 Z=3 -> match; i=6 Z=0; i=7 Z=1. So matches at i=3 and i=5 => positions 0 and 2. Good.
Thus code works.
Now we need to output each match on separate line. Could be zero-based. The problem didn't specify, but it's typical in programming contests to output 0-based indices. We'll do that.
We'll also consider that input may have multiple lines? Possibly pattern and text might be on same line? Usually pattern first line, text second line. We'll assume that.
We'll also handle cases where there are extra whitespace lines: we'll strip.
We'll include comments to explain Z-algorithm.
Now final answer: Provide the program.
But the user asked: "Write a program that implements the Z-algorithm for pattern matching." They may expect just the algorithm implementation, maybe in any language. Since not specified, Python is safe. I'll write a clear, well-commented program.
I'll also include an example usage in comments.
Let's produce final answer.
python
import sys
def z_array(s: str) -> list:
"""
Compute the Z-array for string s.
Z[i] = length of the longest substring starting at i that matches the prefix of s.
"""
n = len(s)
z = [0] * n
l, r = 0, 0 # left and right boundaries of the current Z-box
for i in range(1, n):
if i <= r:
# i is inside the current Z-box
k = i - l
if z[k] < r - i + 1:
# The Z value at k can be safely copied
z[i] = z[k]
else:
# We need to extend the Z-box
l = i
while r < n and s[r] == s[r - l]:
r += 1
z[i] = r - l
r -= 1
else:
# Start a new Z-box from i
l = i
r = i
while r < n and s[r] == s[r - l]:
r += 1
z[i] = r - l
r -= 1
return z
def main() -> None:
# Read pattern and text from standard input.
data = sys.stdin.read().splitlines()
if len(data) < 2:
return
pattern = data[0].rstrip('\n')
text = data[1].rstrip('\n')
if not pattern:
# Empty pattern: no matches (or could be defined as every position, but we skip).
return
# Concatenate pattern and text; the prefix is the pattern.
concat = pattern + text
z = z_array(concat)
p_len = len(pattern)
# For every position in the text part, a full match occurs when Z equals pattern length.
matches = []
for i in range(p_len, len(concat)):
if z[i] == p_len:
# The match starts at index (i - p_len) in the original text.
matches.append(i - p_len)
# Output each match index on its own line.
for pos in matches:
print(pos)
if __name__ == "__main__":
main()