![]() |
VOOZH | about |
Given a string s, find the length of the longest proper prefix which is also a suffix. A proper prefix is a prefix that doesn’t include whole string. For example, prefixes of "abc" are "", "a", "ab" and "abc" but proper prefixes are "", "a" and "ab" only.
Examples:
Input: s = "aabcdaabc"
Output: 4
Explanation: The string "aabc" is the longest proper prefix which is also the suffix.Input: s = "ababab"
Output: 4
Explanation: The string "abab" is the longest proper prefix which is also the suffix.Input: s = "aaaa"
Output: 3
Explanation: The string "aaa" is the longest proper prefix which is also the suffix.
Table of Content
The idea is to compare each proper prefix of the string with its corresponding suffix. A proper prefix has a length ranging from 0 to n - 1. For each possible length, we check if the prefix of that size matches the suffix of the same size. If a match is found, we update the result with the maximum matching length. This brute-force method ensures we find the longest prefix which is also a suffix.
4
The idea is to use the preprocessing step of the KMP (Knuth-Morris-Pratt) algorithm. In this step, we construct an LPS (Longest Prefix Suffix) array, where each index i stores the length of the longest proper prefix of the substring str[0...i] that is also a suffix of the same substring. The value at the last index of the LPS array represents the length of the longest proper prefix which is also a suffix for the entire string.
4
Time Complexity: O(n) we iterate through the string once using the i pointer, and in the worst case, each character is processed at most twice (once when matched, once when falling back via len = lps[len - 1]).
Auxiliary Space: O(n)
The idea is to use double rolling hash to compute and compare the hash values of the prefix and suffix of every possible length from 1 to n-1.
We update prefix and suffix hashes in each iteration and check if they match. If both hashes match, we update the result with the current length. Using two moduli reduces the risk of hash collisions and ensures correctness.
Step by Step Implementation: