Maximum Product of the Length of Two Palindromic Substrings Problem
Description
LeetCode Problem 1960.
You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.
More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive.
Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings.
A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "ababbb"
Output: 9
Explanation: Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Example 2:
Input: s = "zaaaxbbby"
Output: 9
Explanation: Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.
Constraints:
2 <= s.length <= 10^5sconsists of lowercase English letters.
Solution
Approach: Manacher + Prefix/Suffix Maxima
Both substrings must have odd length, so each one is described by its center. Manacher's algorithm gives hlen[i], the largest radius of an odd palindrome centered at i, in linear time.
Let prefix[i] be the longest odd palindrome that ends at or before i, and suffix[i] the longest one that starts at or after i. The palindrome centered at i with radius hlen[i] ends at i + hlen[i], so we first record its length 2 * hlen[i] + 1 there (and symmetrically at i - hlen[i] for suffix). A palindrome that ends at j also has a palindrome two characters shorter that ends at j - 1 (strip both ends), so we sweep to propagate prefix[j - 1] >= prefix[j] - 2, and the mirrored rule for suffix. A second sweep turns the "ends exactly at" values into "ends at or before" values (running maximum), and likewise for suffix.
The answer is the maximum of prefix[i - 1] * suffix[i] over all split points i.
Complexity: O(n) time and O(n) space, where n is the length of s.
class Solution:
def maxProduct(self, s: str) -> int:
n = len(s)
hlen = [0] * n
center = right = 0
for i in range(n):
if i < right:
hlen[i] = min(right - i, hlen[2 * center - i])
while (
0 <= i - 1 - hlen[i]
and i + 1 + hlen[i] < len(s)
and s[i - 1 - hlen[i]] == s[i + 1 + hlen[i]]
):
hlen[i] += 1
if right < i + hlen[i]:
center, right = i, i + hlen[i]
prefix = [0] * n
suffix = [0] * n
for i in range(n):
prefix[i + hlen[i]] = max(prefix[i + hlen[i]], 2 * hlen[i] + 1)
suffix[i - hlen[i]] = max(suffix[i - hlen[i]], 2 * hlen[i] + 1)
for i in range(1, n):
prefix[~i] = max(prefix[~i], prefix[~i + 1] - 2)
suffix[i] = max(suffix[i], suffix[i - 1] - 2)
for i in range(1, n):
prefix[i] = max(prefix[i - 1], prefix[i])
suffix[~i] = max(suffix[~i], suffix[~i + 1])
return max(prefix[i - 1] * suffix[i] for i in range(1, n))