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: We can select "ab" from s and "a" from t to form "aba", which is a palindrome of length 3. This is the maximum possible length.

Constraints

  • 0 ≤ 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 = "ab" a b idx 0 idx 1 String t = "ba" b a idx 0 idx 1 Goal: Concatenate substrings from s and t to form longest palindrome s = "ab", t = "ba" ALGORITHM STEPS 1 Expand Around Centers Try each position as center 2 Check All Combinations s[i..j] + t[k..l] for all 3 Match Characters Expand while chars match 4 Track Maximum Keep longest palindrome Example Expansion: s[0..1]="ab" + t[0]="b" "aba" is palindrome! Length = 3 <-- expand -- -- expand --> FINAL RESULT Longest Palindrome Found: a b a from s from s from t Reads same forwards/backwards "aba" == "aba" [OK] Output: 3 Maximum length achieved! Key Insight: The "Expand Around Centers" approach works by treating each possible position in the concatenated string as a potential palindrome center. We expand outward while characters match. For s="ab" and t="ba", taking substring "ab" from s and "a" from t gives "aba" - a palindrome of length 3, which is the maximum possible. TutorialsPoint - Longest Palindrome After Substring Concatenation I | Expand Around Centers Approach
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