Maximize Palindrome Length From Subsequences - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: word1 = "cacb", word2 = "cbba"
Output: 5
💡 Note: Choose subsequence "ab" from word1 and "cba" from word2 to form "abcba" which is a palindrome of length 5
Example 2 — Simple Match
$ Input: word1 = "ab", word2 = "ba"
Output: 3
💡 Note: Choose "ab" from word1 and "a" from word2 to get "aba", or "a" from word1 and "ba" from word2 to get "aba"
Example 3 — No Valid Palindrome
$ Input: word1 = "aa", word2 = "bb"
Output: 0
💡 Note: Cannot form a palindrome that uses characters from both strings - "aab", "abb", "aabb" are not palindromes

Constraints

  • 1 ≤ word1.length, word2.length ≤ 1000
  • word1 and word2 consist of lowercase English letters.

Visualization

Tap to expand
Maximize Palindrome Length From Subsequencesword1 = "cacb"word2 = "cbba"Pick subsequence:"ab"Pick subsequence:"cba"Concatenate: "ab" + "cba" = "abcba""abcba" is palindrome!Output: Length = 5
Understanding the Visualization
1
Input
Two strings word1 and word2
2
Process
Find subsequences from each that form longest palindrome when concatenated
3
Output
Length of longest valid palindrome
Key Takeaway
🎯 Key Insight: The challenge is finding subsequences from each string that form the longest palindrome when concatenated, requiring both strings to contribute at least one character.
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~35 min Avg. Time
890 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