Maximize Palindrome Length From Subsequences - Problem
Imagine you have two strings word1 and word2, and you want to create the longest possible palindrome by cleverly combining parts of both strings.
Here's how it works:
- Pick any non-empty subsequence from
word1(remember, a subsequence maintains the original order but can skip characters) - Pick any non-empty subsequence from
word2 - Concatenate them as
subsequence1 + subsequence2 - Check if the result is a palindrome
Your goal is to find the maximum length of such a palindrome. If no palindromes can be formed this way, return 0.
Example: If word1 = "cacb" and word2 = "cbba", you could pick "ca" from word1 and "ac" from word2 to form "caac", which is a palindrome of length 4.
Input & Output
example_1.py โ Basic Case
$
Input:
word1 = "cacb", word2 = "cbba"
โบ
Output:
5
๐ก Note:
Choose "cab" from word1 and "ba" from word2 to form "cabba", which is a palindrome with length 5. This is the maximum possible length.
example_2.py โ No Common Characters
$
Input:
word1 = "ab", word2 = "de"
โบ
Output:
0
๐ก Note:
No matter which subsequences we choose from each word, we cannot form a palindrome when concatenating them, so the answer is 0.
example_3.py โ Single Character Match
$
Input:
word1 = "aa", word2 = "bb"
โบ
Output:
0
๐ก Note:
We need at least one character from each word, but 'a' โ 'b', so we cannot form any palindrome by concatenating subsequences from both words.
Constraints
- 1 โค word1.length, word2.length โค 1000
- word1 and word2 consist of lowercase English letters only
- You must choose at least one character from each word
- The resulting string must be a valid palindrome
Visualization
Tap to expand
Understanding the Visualization
1
Survey Available Materials
Examine all the building blocks (characters) available in both cities (word1 and word2)
2
Plan the Bridge Structure
Use dynamic programming to efficiently plan all possible symmetrical bridge configurations
3
Ensure Cross-City Construction
Make sure the bridge uses materials from both cities by checking for palindromes that span the boundary
4
Find the Longest Bridge
Select the configuration that creates the longest possible symmetrical bridge
Key Takeaway
๐ฏ Key Insight: The secret is to use dynamic programming on the concatenated string while ensuring our palindrome crosses the boundary between the two original words, guaranteeing we use materials from both cities.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code