Solving Leetcode Interviews in Seconds with AI: Maximize Palindrome Length From Subsequences
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1771" 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 two strings, word1 and word2. You want to construct a string in the following manner: Choose some non-empty subsequence subsequence1 from word1. Choose some non-empty subsequence subsequence2 from word2. Concatenate the subsequences: subsequence1 + subsequence2, to make the string. Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0. A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward. Example 1: Input: word1 = "cacb", word2 = "cbba" Output: 5 Explanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome. Example 2: Input: word1 = "ab", word2 = "ab" Output: 3 Explanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome. Example 3: Input: word1 = "aa", word2 = "bb" Output: 0 Explanation: You cannot construct a palindrome from the described method, so return 0. Constraints: 1 <= word1.length, word2.length <= 1000 word1 and word2 consist of lowercase English letters.
Explanation
Here's the breakdown of the approach and the Python code:
- Key Idea: Find the longest common palindromic subsequence that can be formed by combining subsequences from
word1andword2. Focus on characters that match between the two words, and then find the longest palindromic subsequence around those matching characters. - Optimization: Use dynamic programming to efficiently calculate the lengths of palindromic subsequences. Start by considering the longest possible palindrome and work inward.
Palindrome Center: Matching characters between
word1andword2will form the "center" of potential palindromes. Extend outward from these centers.Complexity: Time: O(m*n), where m and n are the lengths of
word1andword2respectively. Space: O(m*n).
Code
def longestPalindrome(word1: str, word2: str) -> int:
s = word1 + word2
n1 = len(word1)
n2 = len(word2)
n = len(s)
dp = [[0] * n for _ in range(n)]
ans = 0
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
if i < n1 and j >= n1:
ans = max(ans, dp[i][j])
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return ans