#3503
Longest Palindrome After Substring Concatenation I
MediumTwo PointersStringDynamic ProgrammingEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Count the frequency of characters in both strings. The longest palindrome can be formed by using pairs of characters from both strings, plus one odd character if available.
⚙️
Algorithm
3 steps- 1Step 1: Count character frequencies in both strings.
- 2Step 2: Calculate the total length of pairs from both strings.
- 3Step 3: Add 1 if any character has an odd count for the center of the palindrome.
solution.py6 lines
1from collections import Counter
2
3def longestPalindrome(s, t):
4 count = Counter(s) + Counter(t)
5 length = sum(v // 2 * 2 for v in count.values())
6 return length + (1 if any(v % 2 for v in count.values()) else 0)ℹ
Complexity note: Counting characters is linear, O(n), and we only store counts, leading to O(n) space complexity.
- 1Character pairs form the basis of palindromes.
- 2Odd counts can contribute a single character to the center.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.