Longest Palindrome After Substring Concatenation I - 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.

A palindrome is a string that reads the same forwards and backwards.

Input & Output

Example 1 — Basic Case
$ Input: s = "ab", t = "ba"
Output: 3
💡 Note: Select substring "a" from s and "ba" from t to form "aba", which is a palindrome of length 3. This is the maximum possible.
Example 2 — Single Character
$ Input: s = "x", t = "y"
Output: 1
💡 Note: Best we can do is select "x" from s (and empty from t) or "y" from t (and empty from s), giving palindromes of length 1.
Example 3 — Identical Strings
$ Input: s = "abc", t = "abc"
Output: 3
💡 Note: Select "a" from s and "bc" from t to get "abc", or "ab" from s and "c" from t to get "abc". Neither is palindrome. Best is single characters like "a", "b", or "c" with length 1, but "cac" from "c"+"a"+"c" isn't valid since we need s+t order. Actually "aba" can be formed by selecting "ab" from s and "a" from t... wait, that gives "aba" which works! Length 3.

Constraints

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

Visualization

Tap to expand
Longest Palindrome from String ConcatenationString s:abString t:baSelect substrings and concatenate:"a"+"ba"="aba"from sfrom tpalindrome!Check: a-b-a reads same forwards and backwards ✓Maximum Palindrome Length: 3Try all combinations to find the longest palindrome possible
Understanding the Visualization
1
Input Strings
Two strings s and t with potential substrings
2
Combine Substrings
Select substring from s + substring from t
3
Find Longest Palindrome
Return maximum length palindrome possible
Key Takeaway
🎯 Key Insight: Every palindrome can be formed by carefully selecting complementary substrings from both input strings
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
30.3K Views
Medium Frequency
~25 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