#1960

Maximum Product of the Length of Two Palindromic Substrings

Hard
Two PointersStringRolling HashHash FunctionTwo PointersDynamic ProgrammingString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using Manacher's algorithm allows us to efficiently find all odd-length palindromic substrings in linear time. We can then use a two-pointer technique to find the maximum product of the lengths of non-overlapping palindromic substrings.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use Manacher's algorithm to find the lengths of the longest odd-length palindromic substrings centered at each index.
  2. 2Step 2: Create two arrays to store the maximum lengths of palindromes to the left and right of each index.
  3. 3Step 3: Iterate through the string, and for each center, calculate the maximum product of lengths of non-overlapping palindromic substrings using the precomputed lengths.
solution.py30 lines
1def manachers_algorithm(s):
2    n = len(s)
3    p = [0] * n
4    center = right = 0
5    for i in range(n):
6        mirror = 2 * center - i
7        if i < right:
8            p[i] = min(right - i, p[mirror])
9        a, b = i + (1 + p[i]), i - (1 + p[i])
10        while a < n and b >= 0 and s[a] == s[b]:
11            p[i] += 1
12            a += 1
13            b -= 1
14        if i + p[i] > right:
15            center, right = i, i + p[i]
16    return p
17
18def max_product(s):
19    n = len(s)
20    p = manachers_algorithm(s)
21    left_max = [0] * n
22    right_max = [0] * n
23    for i in range(n):
24        left_max[i] = p[i] if i == 0 else max(left_max[i - 1], p[i])
25    for i in range(n - 1, -1, -1):
26        right_max[i] = p[i] if i == n - 1 else max(right_max[i + 1], p[i])
27    max_product = 0
28    for i in range(n - 1):
29        max_product = max(max_product, left_max[i] * right_max[i + 1])
30    return max_product

Complexity note: The time complexity is O(n) due to the linear scan of the string for Manacher's algorithm. The space complexity is O(n) because we store the lengths of palindromes and the maximum lengths in separate arrays.

  • 1Using Manacher's algorithm is crucial for efficiency.
  • 2Understanding non-overlapping conditions is key to maximizing the product.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.