#2484
Count Palindromic Subsequences
HardStringDynamic ProgrammingDynamic ProgrammingCombinatorial Counting
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 solution leverages dynamic programming to efficiently count palindromic subsequences of length 5 by focusing on the first and last characters and using previously computed results to build up to the desired length.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP table to store counts of palindromic subsequences for different lengths.
- 2Step 2: Iterate through the string, updating the DP table based on matching characters and previously computed values.
- 3Step 3: Return the count of palindromic subsequences of length 5 from the DP table.
solution.py17 lines
1def countPalindromicSubsequences(s):
2 mod = 10**9 + 7
3 n = len(s)
4 dp = [[0] * n for _ in range(n)]
5
6 for i in range(n):
7 dp[i][i] = 1
8
9 for length in range(2, n + 1):
10 for left in range(n - length + 1):
11 right = left + length - 1
12 if s[left] == s[right]:
13 dp[left][right] = dp[left + 1][right] + dp[left][right - 1] + 1
14 else:
15 dp[left][right] = dp[left + 1][right] + dp[left][right - 1] - dp[left + 1][right - 1]
16
17 return sum(dp[i][j] for i in range(n) for j in range(n) if j - i + 1 == 5) % modℹ
Complexity note: The time complexity is O(n²) due to the nested loops for filling the DP table. The space complexity is also O(n²) because we store results for all pairs of indices in the DP table.
- 1Focus on character matching to build palindromic subsequences.
- 2Dynamic programming can optimize counting by reusing results.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.