Problem Description
Given a string s, find two non-intersecting odd-length palindromic substrings such that the product of their lengths is maximized. More formally, you need to choose indices i, j, k, l with 0 <= i <= j < k <= l < s.length so that both s[i...j] and s[k...l] are palindromes (each of odd length). Return the maximum product of their lengths.
Key Insights
- Odd-length palindromes can be centered around each character. Use a method (like Manacher’s algorithm) to compute palindrome radii.
- For every center, the maximum odd palindrome length is given by 2 * radius + 1.
- Precompute two arrays:
- left[i]: the maximum odd palindrome length ending at or before index i.
- right[i]: the maximum odd palindrome length starting at or after index i.
- The answer is obtained by considering all possible splits (non-intersecting condition) and maximizing left[j] * right[j+1].
Space and Time Complexity
Time Complexity: O(n), where n is the length of s (after using Manacher’s algorithm). Space Complexity: O(n) for storing the arrays of palindrome radii and the left/right maximum palindrome lengths.
Solution
We start by computing the palindrome radius for every center of the string using Manacher’s algorithm. Each center at index i gives a radius r such that the substring from i-r to i+r is a palindrome with odd length 2*r+1.
Next, we build:
- A left array where left[i] is defined as the maximum palindrome length among all palindromes ending at or before i. For a palindrome centered at i with radius r, it ends at i+r.
- A right array where right[i] is defined as the maximum palindrome length among all palindromes starting at or after i. For a palindrome centered at i with radius r, it starts at i-r.
After these precomputation steps, iterate over possible division points between the two substrings. For each valid split index j (where the first palindrome ends at or before j and the second starts at j+1), update the maximum product as left[j] * right[j+1].
Data Structures & Techniques:
- An array to store the computed radius for each center using Manacher’s algorithm.
- Two auxiliary arrays to keep track of the maximum odd palindrome lengths ending at or before an index (left) and starting at or after an index (right).
- A final loop over the potential split index to determine the maximum product.
Important Gotchas:
- Ensure palindromes are of odd length only.
- Non-intersecting condition is guaranteed by considering a split between indices.