Solving Leetcode Interviews in Seconds with AI: Maximum Product of the Length of Two Palindromic Substrings
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1960" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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.
Explanation
Here's a breakdown of the solution approach, followed by the code:
- Palindrome Expansion: Efficiently identify all odd-length palindromic substrings centered at each index by expanding outwards.
- Prefix and Suffix Max Lengths: Precompute two arrays:
left_maxandright_max.left_max[i]stores the maximum length of an odd-length palindromic substring ending at or before indexi.right_max[i]stores the maximum length of an odd-length palindromic substring starting at or after indexi. Maximize Product: Iterate through all possible split points in the string, using
left_maxandright_maxto efficiently calculate the product of the maximum palindrome lengths on either side, and keep track of the global maximum.Runtime Complexity: O(n), Storage Complexity: O(n)
Code
def maxProduct(s: str) -> int:
n = len(s)
left_max = [0] * n
right_max = [0] * n
def expand_palindrome(left: int, right: int) -> int:
while left >= 0 and right < n and s[left] == s[right]:
left -= 1
right += 1
return right - left - 1
# Calculate left_max
max_len = 0
for i in range(n):
curr_len = expand_palindrome(i, i)
max_len = max(max_len, curr_len)
left_max[i] = max_len
# Calculate right_max
max_len = 0
for i in range(n - 1, -1, -1):
curr_len = expand_palindrome(i, i)
max_len = max(max_len, curr_len)
right_max[i] = max_len
# Calculate maximum product
max_product = 0
for i in range(n - 1):
max_product = max(max_product, left_max[i] * right_max[i + 1])
return max_product