#3472
Longest Palindromic Subsequence After at Most K Operations
MediumStringDynamic ProgrammingDynamic ProgrammingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^n) | O(n^2 * k) |
| Space | O(n) | O(n^2 * k) |
💡
Intuition
Time O(n^2 * k)Space O(n^2 * k)
Use dynamic programming to build a table that tracks the longest palindromic subsequence lengths while considering the cost of character replacements.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a 3D DP array dp[i][j][k] to store lengths of palindromic subsequences from index i to j with k operations.
- 2Step 2: Fill the DP table based on character matches and allowable operations.
- 3Step 3: Return dp[0][n-1][k] for the final result.
solution.py11 lines
1def longest_palindromic_subseq(s, k):
2 n = len(s)
3 dp = [[[0] * (k + 1) for _ in range(n)] for _ in range(n)]
4 for length in range(1, n + 1):
5 for i in range(n - length + 1):
6 j = i + length - 1
7 if s[i] == s[j]:
8 dp[i][j][0] = dp[i + 1][j - 1][0] + 2
9 for ops in range(1, k + 1):
10 dp[i][j][ops] = max(dp[i][j][ops], dp[i + 1][j][ops - 1], dp[i][j - 1][ops - 1])
11 return dp[0][n - 1][k]ℹ
Complexity note: Quadratic in terms of string length and linear in terms of operations due to the 3D DP table.
- 1Character replacements can help form palindromes.
- 2Dynamic programming efficiently tracks subsequence lengths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.