Maximum Product of the Length of Two Palindromic Substrings - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "ababbb"
Output: 9
💡 Note: The optimal split is at position 3. Left part "aba" has palindrome "aba" (length 3), right part "bbb" has palindrome "bbb" (length 3). Product: 3 × 3 = 9.
Example 2 — Single Characters
$ Input: s = "zaba"
Output: 3
💡 Note: Split at position 1: left "z" has palindrome "z" (length 1), right "aba" has palindrome "aba" (length 3). Product: 1 × 3 = 3.
Example 3 — No Valid Split
$ Input: s = "aa"
Output: 0
💡 Note: We need odd-length palindromes. "aa" has even length, so there's no way to find two non-intersecting odd-length palindromes.

Constraints

  • 2 ≤ s.length ≤ 105
  • s consists of lowercase English letters only

Visualization

Tap to expand
Maximum Product of Palindromic Substrings INPUT String s = "ababbb" a 0 b 1 a 2 b 3 b 4 b 5 Requirements: - Find 2 non-intersecting palindromic substrings - Both must have ODD length - Maximize: len1 * len2 Odd-length palindromes: "aba" (3) "bbb" (3) "a" (1) "b" (1) ALGORITHM STEPS 1 Expand Around Centers For each index, expand outward to find palindromes 2 Compute maxLeft[] maxLeft[i] = max palindrome length ending at or before i 3 Compute maxRight[] maxRight[i] = max palindrome length starting at or after i 4 Find Max Product For each split point k: max(maxLeft[k-1]*maxRight[k]) Best Split at k=3: "aba" | "bbb" len=3 * len=3 = 9 FINAL RESULT Optimal non-intersecting pair: Palindrome 1: "aba" Position: 0-2, Length: 3 Palindrome 2: "bbb" Position: 3-5, Length: 3 a b a b b b Product = 3 x 3 = 9 Output: 9 Key Insight: The Expand Around Centers approach processes each character as a potential palindrome center. By precomputing maxLeft[] and maxRight[] arrays, we can efficiently find the best split point that maximizes the product of two non-overlapping odd-length palindromes in O(n) time. TutorialsPoint - Maximum Product of the Length of Two Palindromic Substrings | Expand Around Centers Approach
Asked in
Google 15 Amazon 12 Microsoft 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen