Longest Palindrome After Substring Concatenation I - Problem

You're a word puzzle master creating the longest possible palindrome by combining pieces from two different strings!

Given two strings s and t, you can pick any substring (including empty ones) from each string and concatenate them to form: substring_from_s + substring_from_t.

Goal: Find the length of the longest palindrome you can create this way.

Example: If s = "abc" and t = "cba", you could take "ab" from s and "a" from t to make "aba" (length 3), or take "a" from s and "ba" from t to make "aba" again!

Input & Output

example_1.py β€” Basic Case
$ Input: s = "abc", t = "def"
β€Ί Output: 1
πŸ’‘ Note: We can take empty string from s and "d" from t to form "d" (length 1), or "a" from s and empty string from t to form "a" (length 1). Both are palindromes of length 1.
example_2.py β€” Perfect Match
$ Input: s = "ab", t = "ba"
β€Ί Output: 4
πŸ’‘ Note: We can take "ab" from s and "ba" from t to form "abba" which is a palindrome of length 4. This is the maximum possible.
example_3.py β€” Partial Overlap
$ Input: s = "abc", t = "cba"
β€Ί Output: 3
πŸ’‘ Note: We can take "a" from s and "ba" from t to form "aba" (length 3), or "ab" from s and "a" from t to form "aba" (length 3). Both give us palindromes of length 3.

Visualization

Tap to expand
String S"abc"Substrings: "", "a", "b", "c", "ab", "bc", "abc"String T"cba"Substrings: "", "c", "b", "a", "cb", "ba", "cba"Combination Example"ab" + "a" = "aba"βœ“ Palindrome (Length: 3)LRTwo Pointers Check:Compare 'a' == 'a' βœ“, then 'b' (middle)
Understanding the Visualization
1
Enumerate Substrings
Generate all possible substring combinations from both input strings
2
Virtual Concatenation
Conceptually combine substrings without creating new strings
3
Palindrome Verification
Use two pointers to check if the combination forms a palindrome
4
Track Maximum
Keep track of the longest palindrome found during enumeration
Key Takeaway
🎯 Key Insight: We systematically enumerate all possible substring combinations and use efficient two-pointer palindrome checking to find the maximum length palindrome without creating temporary strings.

Time & Space Complexity

Time Complexity
⏱️
O(nΒ²mΒ²(n+m))

Same enumeration complexity but with optimized palindrome checking

n
2n
⚠ Quadratic Growth
Space Complexity
O(1)

Only uses constant extra space for pointers, no string concatenation

n
2n
βœ“ Linear Space

Constraints

  • 1 ≀ s.length, t.length ≀ 1000
  • s and t consist of lowercase English letters only
  • Substrings can be empty (length 0)
  • The concatenation order is always s_substring + t_substring
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~25 min Avg. Time
886 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