{x}
blog image

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 <= 105
  • s consists of lowercase English letters.

Solution Explanation and Code for Maximum Product of the Length of Two Palindromic Substrings

This problem asks us to find two non-overlapping palindromic substrings of odd length within a given string and return the maximum product of their lengths.

Approach

The most straightforward approach involves iterating through all possible odd-length substrings, checking if they are palindromes, and then finding the maximum product of lengths for non-overlapping pairs. We can optimize this by using a technique to efficiently identify palindromes.

1. Identifying Palindromes:

We can use a simple helper function to check if a substring is a palindrome. This function would take the substring's start and end indices as input and return True if it's a palindrome, False otherwise.

2. Iterating and Finding the Maximum Product:

We'll iterate through the string. For each potential starting point of a palindrome, we will expand outwards to find the longest odd-length palindrome starting at that point.

Once we have the first palindrome, we then search for the second palindrome starting after the first one. We iterate through all possible starting positions for the second palindrome ensuring it doesn't overlap with the first. We record the maximum product found.

Time and Space Complexity Analysis

  • Time Complexity: O(n^2), where n is the length of the string. This is because we might need to iterate through all possible pairs of substrings. In the worst case, we examine all substrings.
  • Space Complexity: O(1). We only store a few variables; the space usage is constant regardless of input size.

Code Implementation (Python)

def maxProduct(s):
    """
    Finds the maximum product of lengths of two non-intersecting palindromic substrings.
 
    Args:
        s: The input string.
 
    Returns:
        The maximum product of lengths.
    """
 
    def is_palindrome(sub):
        return sub == sub[::-1]
 
    n = len(s)
    max_prod = 0
 
    for i in range(n):
        for j in range(i, n):
            len1 = j - i + 1
            if len1 % 2 != 0 and is_palindrome(s[i:j+1]):  # Odd length palindrome
                for k in range(j + 1, n):
                    for l in range(k, n):
                        len2 = l - k + 1
                        if len2 % 2 != 0 and is_palindrome(s[k:l+1]): #Odd length palindrome
                            max_prod = max(max_prod, len1 * len2)
 
    return max_prod
 
 
# Example usage:
s1 = "ababbb"
s2 = "zaaaxbbby"
print(f"Maximum product for '{s1}': {maxProduct(s1)}")  # Output: 9
print(f"Maximum product for '{s2}': {maxProduct(s2)}")  # Output: 9
 

Note: While the above code works, it's not the most efficient solution for extremely large strings. More sophisticated algorithms like Manacher's algorithm could be used to improve time complexity for very large inputs, but for moderate-sized strings, this approach is reasonable. The O(n^2) complexity makes it suitable for strings up to a few thousand characters in length, but beyond that, optimization becomes crucial.