#1771
Maximize Palindrome Length From Subsequences
HardStringDynamic ProgrammingDynamic ProgrammingTwo Pointers
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²)
The optimal approach uses dynamic programming to find the longest palindromic subsequence in the concatenated string of word1 and word2. This method is efficient because it systematically builds solutions to subproblems, avoiding redundant calculations.
⚙️
Algorithm
4 steps- 1Step 1: Concatenate word1 and word2 into a new string.
- 2Step 2: Create a 2D DP array where dp[i][j] represents the length of the longest palindromic subsequence in the substring from index i to j.
- 3Step 3: Fill the DP table using the relationships: if characters match, extend the palindrome; if not, take the maximum from the adjacent subproblems.
- 4Step 4: The result will be in dp[0][length-1] where length is the length of the concatenated string.
solution.py16 lines
1# Full working Python code
2
3def max_palindrome_length(word1, word2):
4 combined = word1 + word2
5 n = len(combined)
6 dp = [[0] * n for _ in range(n)]
7 for i in range(n):
8 dp[i][i] = 1
9 for length in range(2, n + 1):
10 for i in range(n - length + 1):
11 j = i + length - 1
12 if combined[i] == combined[j]:
13 dp[i][j] = dp[i + 1][j - 1] + 2
14 else:
15 dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
16 return dp[0][n - 1]ℹ
Complexity note: The time complexity is O(n²) due to the nested loops filling the DP table. The space complexity is also O(n²) because we store results in a 2D array.
- 1Subsequences can be formed by deleting characters without changing order.
- 2Palindromes can be efficiently found using dynamic programming.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.