#3504
Longest Palindrome After Substring Concatenation II
HardTwo PointersStringDynamic ProgrammingHash 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)
Utilize dynamic programming to find the longest palindromic substring in s and t, then combine results. This reduces unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Preprocess s and t to find the longest palindromic substrings that start and end at each index.
- 2Step 2: Use these preprocessed results to calculate the maximum palindrome length by combining valid starting and ending characters.
- 3Step 3: Return the maximum length found.
solution.py15 lines
1def longestPalindrome(s, t):
2 def longest_palindrome_from(s):
3 n = len(s)
4 p = [0] * n
5 for i in range(n):
6 l, r = i, i
7 while l >= 0 and r < n and s[l] == s[r]:
8 p[i] += 1
9 l -= 1
10 r += 1
11 return p
12 p_s = longest_palindrome_from(s)
13 p_t = longest_palindrome_from(t)
14 max_len = max(p_s) + max(p_t)
15 return max_lenℹ
Complexity note: We preprocess each string in linear time, leading to O(n) complexity. Space is used to store palindrome lengths.
- 1Single characters are palindromes.
- 2Combining palindromic substrings maximizes length.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.