Problem Description
Given two strings word1 and word2, we want to choose one non‐empty subsequence from each and then concatenate them to form a string. The task is to find the length of the longest palindromic string (reads the same forwards and backwards) that can be constructed in this way. If no valid palindrome exists (i.e. one that uses at least one character from each word), return 0.
Key Insights
- The result palindrome must have characters coming from both word1 and word2.
- A natural idea is to compute the longest palindromic subsequence (LPS) of the combined string word1 + word2.
- However, you must ensure that the chosen palindrome “crosses the boundary” between the two words (i.e. it has at least one index from word1 and one from word2).
- Use dynamic programming to compute the LPS for any substring and then inspect candidates to ensure they include characters from both word1 and word2.
Space and Time Complexity
Time Complexity: O(n^2), where n is the total length of word1 and word2. Space Complexity: O(n^2) due to the 2D DP table used for computing the longest palindromic subsequence.
Solution
We first combine word1 and word2 into one string s and note the length of word1 (say n1). We build a DP table dp such that dp[i][j] represents the length of the longest palindromic subsequence in the substring s[i...j]. The recurrence is: • If s[i] == s[j], then dp[i][j] = dp[i+1][j-1] + 2 (and if i == j, dp[i][j] = 1). • Otherwise, dp[i][j] = max(dp[i+1][j], dp[i][j-1]). After filling the table, we need to ensure that our palindrome includes at least one character from word1 (indices < n1) and one from word2 (indices >= n1). Thus, we iterate over all pairs i, j such that s[i] == s[j] with i in word1 and j in word2, and update our answer with dp[i][j]. If no candidate is found, return 0.
Key details: • Use a bottom-up tabulation to fill dp. • Carefully iterate over possible boundary-crossing pairs to satisfy the problem’s constraint.