1. Understand the Goal: The user wants a program that implements the Z-algorithm for pattern matching.
Identify the Core Algorithm:
What is the Z-algorithm? It's an algorithm for finding occurrences of a "pattern" string within a "text" string.
How does it work? It constructs a "Z-array" for a concatenated string: Pattern + Sentinel + Text.
What is the Z-array? Z[i] is the length of the longest substring starting at index i that is also a prefix of the string starting at index 0.
What is the logic for constructing the Z-array?
Naive approach: O(N2).
Optimized approach: O(N) using the "Z-box" concept.
Maintain a window [L,R] which is the interval with maximum R such that [L,R] is a prefix substring.
Case 1: (current index is outside the known Z-box). Reset and match forward.
Determine the Input/Output:
Input: Two strings, usually text and pattern.
Output: A list of indices where the pattern occurs in the text (0-based or 1-based).
Select a Programming Language: Python is generally the most readable and widely understood for algorithmic demonstrations, but C++ is also popular for competitive programming. I will provide the solution in Python for clarity, perhaps with a C++ version as an alternative or just stick to Python with clear comments. Let's stick to Python as the primary, maybe add C++ if requested, but for a general request, Python is safest.
Drafting the Code (Mental or Scratchpad):
Step 1: Z-array construction function.
python
def get_z_array(s):
n = len(s)
z = [0] * n
l, r = 0, 0
for i in range(1, n):
# Logic here
Step 2: Refine Z-array logic.
python
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
Wait, there's a subtle bug in the logic above often made.
Specifically if z[k] < r - i + 1. The distance from i to R is R−.
Actually, a cleaner way to write the condition often used is:
If :
Then, extend matches if we hit the boundary.
Refining the Code Structure:
I should create a class or a clean function structure.
z_algorithm(concatenated_string): returns the Z-array.
search(text, pattern): uses the Z-array function to find matches.
Writing the Explanation:
The user needs to understand how it works, not just copy-paste. I should explain:
The concatenation trick.
What the Z-array represents.
The Z-box optimization (L,R).
Time Complexity (O(N+M)).
Final Code Polish (Python):
python
def z_algorithm(s):
n = len(s)
z = [0] * n
l, r = 0, 0
for i in range(1, n):
if i <= r:
# If i is within the current Z-box [L, R]
# The value is at least the minimum of the boundary or the mirrored value
z[i] = min(r - i + 1, z[i - l])
# Try to extend the Z-value
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
# If we went past R, update the box
if i + z[i] - 1 > r:
l = i
r = i + z[i] - 1
return z
def pattern_match(text, pattern):
# Concatenate Pattern + Special Char + Text
concat = pattern + "$" + text
z = z_algorithm(concat)
matches = []
len_p = len(pattern)
len_z = len(z)
for i in range(len_z):
if z[i] == len_p:
# The index in the original text is i - len(pattern) - 1
# Because: index i in concat corresponds to index i - (len_p + 1) in text
matches.append(i - len_p - 1)
return matches
Double Check:
Index arithmetic: concat = pattern + "$" + text. len(concat) = P + 1 + T.
At index i in concat, if z[i] == P, the match starts at i.
To map i back to text: text starts at index P + 1 in concat.
Values:
0: 0 (length of string)
1: 0 (b!=a)
2: 0 (c!=a)
3: 0 ($!=a)
4: 3 (matches abc) -> Match found. Index in text = 4 - 3 - 1 = 0. Correct.
5: 0 (b!=a)
6: 0 (c!=a)
7: 2 (ab matches prefix) -> Not a full match.
8: 0
Wait, what if z[i] is calculated as min(...)?
Let's trace the min logic again.
if i <= r: z[i] = min(r - i + 1, z[i - l])
This covers the subcases 2a and 2b efficiently.
If z[i - l] fits in the box, take it.
If it hits the edge, take the distance to the edge, then start expanding.
This logic is correct and standard.
Output Formatting: Provide the code, then a usage example, then a brief complexity analysis. This adds value. I will provide both Python and C++ since Z-algorithm is very common in C++ competitive programming contexts.
Final Review of the prompt: "Write a program that implements the Z-algorithm for pattern matching."
Does it need to be a specific language? No.
Does it need to handle edge cases? Yes (empty strings, no matches).
Self-correction on Python implementation details: The naive implementation inside the while loop is fine, but the initialization of z[0] is usually n or 0. Standard convention is usually 0 or the length of the string. Since Z[0] is defined as the number of characters matching the prefix starting at 0, it is the string length. However, usually, the algorithm is defined from i=1 to N−1. I will set or (it doesn't matter for pattern matching as long as we iterate from 1). I'll stick to the standard implementation where the loop starts at 1.
How it works
The Z-Algorithm constructs a Z-array where Z[i] stores the length of the longest substring starting from index i that matches the prefix of the string starting at index 0.
To use this for pattern matching:
Concatenate the Pattern, a special separator character (like $), and the Text.
Compute the Z-array for this concatenated string.
Iterate through the Z-array. If a value Z[i] is equal to the length of the pattern, it means the pattern was found at that index.
Python Implementation
python
def calculate_z_array(s):
"""
Computes the Z-array for a given string s.
Time Complexity: O(n)
"""
n = len(s)
z = [0] * n
l, r = 0, 0
# Iterate through the string starting from index 1
for i in range(1, n):
# Case 1: i is outside the current Z-box [l, r]
if i > r:
l = r = i
# Expand r as long as characters match
while r < n and s[r - l] == s[r]:
r += 1
z[i] = r - l
r -= 1
# Case 2: i is inside the current Z-box [l, r]
else:
k = i - l
# If the Z-value at k does not touch the boundary of the box
if z[k] < r - i + 1:
z[i] = z[k]
else:
# Otherwise, we need to do explicit comparisons starting from r
l = i
while r < n and s[r - l] == s[r]:
r += 1
z[i] = r - l
r -= 1
return z
def z_algorithm_search(text, pattern):
"""
Finds all occurrences of pattern in text using the Z-algorithm.
Returns a list of starting indices (0-based).
"""
# 1. Create the combined string
# We use '$' as a separator. Ensure this char is not in the pattern or text.
separator = '$'
combined = pattern + separator + text
# 2. Compute Z-array
z = calculate_z_array(combined)
# 3. Find matches
pattern_len = len(pattern)
matches = []
# We start checking from after the separator index
start_index = pattern_len + 1
for i in range(start_index, len(combined)):
# If Z-value equals pattern length, we found a perfect match
if z[i] == pattern_len:
# Calculate the actual index in the original text
original_index = i - start_index
matches.append(original_index)
return matches
# --- Main Execution Block ---
if __name__ == "__main__":
text_input = "ABABDABACDABABCABAB"
pattern_input = "ABABCABAB"
print(f"Text: {text_input}")
print(f"Pattern: {pattern_input}")
indices = z_algorithm_search(text_input, pattern_input)
if indices:
print(f"Pattern found at indices: {indices}")
else:
print("Pattern not found.")
Explanation of Logic
The Z-Array (calculate_z_array):
We maintain a window [L, R] which is the interval with maximum R such that S[L...R] is a prefix of S.
Case 1 (i > R): We are outside the known matching window. We reset L and R to i and manually compare characters forward to find the new matching length.
Case 2 (i <= R): We are inside the window. This means S[i] matches S[k] (where k = i - L). We can use the previously computed value Z[k] to speed up computation, unless Z[k] exceeds the current window boundary, in which case we must extend manually.
Pattern Matching (z_algorithm_search):
We create a string: Pattern + $ + Text.
When we process this string, the Z-values corresponding to the "Text" portion measure how much the text at that position matches the "Pattern" (which is the prefix).
If Z[i] == len(Pattern), we have a full match.
Complexity
Time Complexity:O(N+M), where N is the length of the text and M is the length of the pattern. The construction of the Z-array is linear because the R pointer only moves forward.
Space Complexity:O(N to store the concatenated string and the Z-array.
i>R
L=i,R=i
Case 2: i≤R (current index is inside the known Z-box). Let k=i−L.
Subcase 2a: Z[k]<R−i+1. Then Z[i]=Z[k].
Subcase 2b: Z[k]≥R−i+1. Match forward starting at R+1 and update Lnew_match_end.
i+
1
i≤R
Z[i]=min(R−i+1,Z[i−L])
Step 3: Integration.
Concatenate string: pattern + "$" + text.
Calculate Z-array.
Iterate Z-array. If Z[i]==len(pattern), found a match.
z[0] = 0
len(s)
Let's refine the Z-algo function one last time for clarity.
The min logic is the elegant way.
The l and r update logic needs to be inside the loop.
The z[0] is usually formally defined as the length of the string, but practically we start the loop at 1. I will initialize z with 0s.
Code Plan:
get_z_array(string)
search(text, pattern)
main block to test.
C++ Plan:
Vector based, similar logic.
I will present the Python solution primarily as it is most accessible.
(Self-Correction on indices):
If concat = pattern + "$" + text.
If z[i] == len(pattern).
The start index of the match in concat is i.
The start index of the match in text is i - (len(pattern) + 1).
Correct.
Ready to write.
Here is a complete implementation of the Z-Algorithm for pattern matching in Python.