HardNo. 0730

Count Different Palindromic Subsequences — LeetCode 730 Python Solution

Topics
String, Dynamic Programming
Reading time
4 min

The problem

Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.

Example

Input
s = "bccb"
Output
6
Explanation
The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.

Python solution

PythonSolution
class Solution:
    def countPalindromicSubsequences(self, s: str) -> int:
        mod = 10**9 + 7
        n = len(s)
        dp = [[[0] * 4 for _ in range(n)] for _ in range(n)]
        for i, c in enumerate(s):
            dp[i][i][ord(c) - ord('a')] = 1
        for l in range(2, n + 1):
            for i in range(n - l + 1):
                j = i + l - 1
                for c in 'abcd':
                    k = ord(c) - ord('a')
                    if s[i] == s[j] == c:
                        dp[i][j][k] = 2 + sum(dp[i + 1][j - 1])
                    elif s[i] == c:
                        dp[i][j][k] = dp[i][j - 1][k]
                    elif s[j] == c:
                        dp[i][j][k] = dp[i + 1][j][k]
                    else:
                        dp[i][j][k] = dp[i + 1][j - 1][k]
        return sum(dp[0][-1]) % mod

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 730. Count Different Palindromic Subsequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0072Edit DistanceMedium
0087Scramble StringHard

Frequently asked questions

How hard is LeetCode 730. Count Different Palindromic Subsequences?

LeetCode 730. Count Different Palindromic Subsequences is rated Hard on LeetCode.

What topics does LeetCode 730. Count Different Palindromic Subsequences cover?

LeetCode 730. Count Different Palindromic Subsequences is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.