Longest Palindrome After Substring Concatenation II - Problem

You are given two strings, s and t. You can create a new string by selecting a substring from s (possibly empty) and a substring from t (possibly empty), then concatenating them in order.

Return the length of the longest palindrome that can be formed this way.

Note: A palindrome is a string that reads the same forward and backward. An empty string is considered a palindrome of length 0.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc", t = "cba"
Output: 6
💡 Note: Take full string from s ("abc") and full string from t ("cba") to form "abccba", which is a palindrome of length 6
Example 2 — Partial Substrings
$ Input: s = "ab", t = "ba"
Output: 4
💡 Note: Take "ab" from s and "ba" from t to form "abba", which is a palindrome of length 4
Example 3 — Empty Substring
$ Input: s = "abc", t = "def"
Output: 1
💡 Note: No good concatenation forms a long palindrome. Best is taking single character like "a" (from s) + "" (empty from t) = "a" with length 1

Constraints

  • 1 ≤ s.length, t.length ≤ 1000
  • s and t consist of lowercase English letters

Visualization

Tap to expand
Longest Palindrome After Substring Concatenation INPUT String s = "abc" a b c String t = "cba" c b a Select substrings: s[0..2] = "abc" t[0..2] = "cba" Concatenate in order: "abc" + "cba" ALGORITHM STEPS 1 Find Matching Pairs Reverse t, check prefix-suffix matches with s 2 Extend Palindrome Find longest palindrome in middle portion 3 Try All Combinations prefix(s) + palindrome + suffix(t) reversed 4 Track Maximum Length Update max when valid palindrome found Best Combination Found: s[0..2] = "abc" t[0..2] = "cba" Result: "abccba" Palindrome: OK FINAL RESULT Longest Palindrome: a b c c b a "abccba" reads same both ways Mirror Point Output: 6 Status: OK s[0..2] + t[0..2] = "abc" + "cba" = 6 chars Maximum possible length Key Insight: The optimal approach uses suffix-prefix matching: if s ends with "abc" and t starts with "cba" (reverse of "abc"), concatenating them creates a palindrome. We also check for additional palindromic extensions in the middle. Time complexity: O(n^2) using dynamic programming for palindrome checking. Space: O(n) for storing results. TutorialsPoint - Longest Palindrome After Substring Concatenation II | Optimal Solution
Asked in
Google 35 Facebook 28 Amazon 22
28.5K Views
Medium Frequency
~35 min Avg. Time
892 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