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 jinclusive.
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.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
"ababbb"
Example 2
"zaaaxbbby"
Related Problems
Maximum Product of the Length of Two Palindromic Subsequences (maximum-product-of-the-length-of-two-palindromic-subsequences)
Minimum Cost to Make Array Equal (minimum-cost-to-make-array-equal)
Step 02
Core Insight
What unlocks the optimal approach
You can use Manacher's algorithm to get the maximum palindromic substring centered at each index
After using Manacher's for each center use a line sweep from the center to the left and from the center to the right to find for each index the farthest center to it with distance ≤ palin[center]
After that, find the maximum palindrome size for each prefix in the string and for each suffix and the answer would be max(prefix[i] * suffix[i + 1])
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1960: Maximum Product of the Length of Two Palindromic Substrings
class Solution {
public long maxProduct(String s) {
int n = s.length();
if (n == 2) return 1;
int[] len = manachers(s);
long[] left = new long[n];
int max = 1;
left[0] = max;
for (int i = 1; i <= n - 1; i++) {
if (len[(i - max - 1 + i) / 2] > max) max += 2;
left[i] = max;
}
max = 1;
long[] right = new long[n];
right[n - 1] = max;
for (int i = n - 2; i >= 0; i--) {
if (len[(i + max + 1 + i) / 2] > max) max += 2;
right[i] = max;
}
long res = 1;
for (int i = 1; i < n; i++) {
res = Math.max(res, left[i - 1] * right[i]);
}
return res;
}
private int[] manachers(String s) {
int len = s.length();
int[] P = new int[len];
int c = 0;
int r = 0;
for (int i = 0; i < len; i++) {
int mirror = (2 * c) - i;
if (i < r) {
P[i] = Math.min(r - i, P[mirror]);
}
int a = i + (1 + P[i]);
int b = i - (1 + P[i]);
while (a < len && b >= 0 && s.charAt(a) == s.charAt(b)) {
P[i]++;
a++;
b--;
}
if (i + P[i] > r) {
c = i;
r = i + P[i];
}
}
for (int i = 0; i < len; i++) {
P[i] = 1 + 2 * P[i];
}
return P;
}
}
// Accepted solution for LeetCode #1960: Maximum Product of the Length of Two Palindromic Substrings
func maxProduct(s string) int64 {
n := len(s)
hlen := make([]int, n)
center, right := 0, 0
for i := 0; i < n; i++ {
if i < right {
mirror := 2*center - i
if mirror >= 0 && mirror < n {
hlen[i] = min(right-i, hlen[mirror])
}
}
for i-1-hlen[i] >= 0 && i+1+hlen[i] < n && s[i-1-hlen[i]] == s[i+1+hlen[i]] {
hlen[i]++
}
if i+hlen[i] > right {
center = i
right = i + hlen[i]
}
}
prefix := make([]int, n)
suffix := make([]int, n)
for i := 0; i < n; i++ {
r := i + hlen[i]
if r < n {
prefix[r] = max(prefix[r], 2*hlen[i]+1)
}
l := i - hlen[i]
if l >= 0 {
suffix[l] = max(suffix[l], 2*hlen[i]+1)
}
}
for i := 1; i < n; i++ {
if n-i-1 >= 0 {
prefix[n-i-1] = max(prefix[n-i-1], prefix[n-i]-2)
}
suffix[i] = max(suffix[i], suffix[i-1]-2)
}
for i := 1; i < n; i++ {
prefix[i] = max(prefix[i-1], prefix[i])
suffix[n-i-1] = max(suffix[n-i], suffix[n-i-1])
}
var res int64
for i := 1; i < n; i++ {
prod := int64(prefix[i-1]) * int64(suffix[i])
if prod > res {
res = prod
}
}
return res
}
# Accepted solution for LeetCode #1960: Maximum Product of the Length of Two Palindromic Substrings
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))
// Accepted solution for LeetCode #1960: Maximum Product of the Length of Two Palindromic Substrings
/**
* [1960] Maximum Product of the Length of Two Palindromic Substrings
*
* 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^5
* s consists of lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/
// discuss: https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn max_product(s: String) -> i64 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1960_example_1() {
let s = "ababbb".to_string();
let result = 9;
assert_eq!(Solution::max_product(s), result);
}
#[test]
#[ignore]
fn test_1960_example_2() {
let s = "zaaaxbbby".to_string();
let result = 9;
assert_eq!(Solution::max_product(s), result);
}
}
// Accepted solution for LeetCode #1960: Maximum Product of the Length of Two Palindromic Substrings
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1960: Maximum Product of the Length of Two Palindromic Substrings
// class Solution {
// public long maxProduct(String s) {
// int n = s.length();
// if (n == 2) return 1;
// int[] len = manachers(s);
// long[] left = new long[n];
// int max = 1;
// left[0] = max;
// for (int i = 1; i <= n - 1; i++) {
// if (len[(i - max - 1 + i) / 2] > max) max += 2;
// left[i] = max;
// }
// max = 1;
// long[] right = new long[n];
// right[n - 1] = max;
// for (int i = n - 2; i >= 0; i--) {
// if (len[(i + max + 1 + i) / 2] > max) max += 2;
// right[i] = max;
// }
// long res = 1;
// for (int i = 1; i < n; i++) {
// res = Math.max(res, left[i - 1] * right[i]);
// }
// return res;
// }
// private int[] manachers(String s) {
// int len = s.length();
// int[] P = new int[len];
// int c = 0;
// int r = 0;
// for (int i = 0; i < len; i++) {
// int mirror = (2 * c) - i;
// if (i < r) {
// P[i] = Math.min(r - i, P[mirror]);
// }
// int a = i + (1 + P[i]);
// int b = i - (1 + P[i]);
// while (a < len && b >= 0 && s.charAt(a) == s.charAt(b)) {
// P[i]++;
// a++;
// b--;
// }
// if (i + P[i] > r) {
// c = i;
// r = i + P[i];
// }
// }
// for (int i = 0; i < len; i++) {
// P[i] = 1 + 2 * P[i];
// }
// return P;
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.