We consider a string of n characters, indexed 1,2,...,n . Your task is to calculate all values of the following functions:
- z(i) denotes the maximum length of a substring that begins at position i and is a prefix of the string. In addition, z(1)=0.
- π(i) denotes the maximum length of a substring that ends at position i, is a prefix of the string, and whose length is at most i-1.
Note that the function z is used in the Z-algorithm, and the function π(i) is used in the KMP algorithm
Example:
Input: s = "abaabca"
Output:
0 0 1 2 0 0 1
0 0 1 1 2 0 1
Input: s = "bbaabcb"
Output:
0 1 0 0 1 0 1
0 1 0 0 1 0 1
Approach: To solve the problem, follow the below idea:
First calculates the z(i) or Z-function using a two-pointer approach, which keeps track of the segment within which we are currently working. After calculating the z(i) function, prints the values.
Next, calculates the pi(i) function by iterating over the string and checking if the current character matches the character at the index equal to the pi(i) function of the previous position. If it does, it increments the pi(i) function for the current position. If it doesn’t, it finds the next smaller possible matching prefix and suffix by using the pi(i) function of the previous index until it finds a match or no more prefixes are left. After calculating the pi(i) function, it prints the values.
Step-by-step algorithm:
- Z-Function Calculation:
- Initialize the Z-function array zFun to store the length of the longest common prefix between s and its suffix starting from each position.
- Iterate through each position in the string starting from the second position.
- If the current position is within the rightmost boundary (right), use precomputed values to initialize zFun[position].
- Extend the Z-function by comparing characters while the characters match, updating zFun[position].
- Update the boundaries (left and right) for the current palindrome.
- Print the Z-function values.
- Prefix Function Calculation:
- Initialize the prefix function array prefixFun to store the length of the longest proper prefix which is also a suffix for each position.
- Iterate through each position in the string starting from the second position.
- Use the previous value of the prefix function (prefixFun[position - 1]) to initialize j.
- Update the prefix function using the previous values while characters don't match.
- Increment the prefix function if characters match.
- Update the prefix function for the current position.
- Print the prefix function values.
Below is the implementation of above approach:
Output0 1 0 0 1 0 1
0 1 0 0 1 0 1
Time Complexity: O(n)
Auxiliary Space: O(n)