Prefix Function
Practice this coding question on Coding Gurukul.
Problem statement
A communication receiver examines a message as characters arrive. After each new character, it records how much of the message beginning is repeated at the current end. These overlap lengths let later matching operations continue without restarting their search from the beginning. Your task Compute the prefix function of s. For each zero-based position i, output the largest k with 0 <= k < i+1 such that the first k characters of s equal the last k characters of s[0..i]. Important details The matched prefix must be proper: the entire current prefix is excluded. Overlapping matches are allowed. If there is no nonempty match, output zero. Compute all values in O(length of s) time; the task is the prefix array itself, not searching for a separate pattern. Worked example For s = ababa, the values are 0 0 1 2 3. At the last position, aba is both the beginning and the end of ababa, giving 3. For s = aaaa, the values are 0 1 2 3 because the entire four-character string is excluded at the final position.
Input format
Read one nonempty lowercase string s.
Output format
Print the prefix-function values in order, separated by spaces.
Constraints
1 <= length of s <= 3000; lowercase English letters only.
Sample input
ababa
Sample output
0 0 1 2 3
Sign in to run or submit a solution in C++, Java or Python.