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 Subsequences INPUT word1 = "cacb" c a c b idx: 0 1 2 3 word2 = "cbba" c b b a idx: 4 5 6 7 Combined: "cacbcbba" c a c b c b b a Find longest palindrome using chars from BOTH words word1 word2 ALGORITHM STEPS 1 Concatenate Strings s = word1 + word2 2 Build DP Table dp[i][j] = longest palindrome subsequence in s[i..j] c a c b c b b a c 1 1 3 3 3 3 3 5 a 1 1 1 1 1 3 5 c 1 1 3 3 3 3 ... ... 3 Check Valid Palindromes Must use chars from both words: i from word1, j from word2, s[i]==s[j] 4 Track Maximum Update ans when matching pair found: dp[i][j] FINAL RESULT Longest Valid Palindrome Subsequence: "bacab" b a c a b palindrome Character Sources: b from word1[3] a from word1[1] c from word1[2] a from word2[3] b from word2[1] Output: 5 Key Insight: Concatenate word1 + word2 and use DP to find longest palindrome subsequence (LPS). The key constraint: valid palindromes MUST include at least one char from each word. When s[i] == s[j] where i is in word1 range and j is in word2 range, update max answer. TutorialsPoint - Maximize Palindrome Length From Subsequences | Optimal Solution (DP)
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