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
Building the Perfect Mirror BridgeCity 1word1 = "cacb"Materials: c,a,c,bCity 2word2 = "cbba"Materials: c,b,b,aBridge: "cabba"Symmetry Checkc-a-b-b-aโ†•a-b-b-a-cPerfect Mirror!Length5Maximum possible bridge length!
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.
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 18
31.5K Views
Medium-High Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen