Count All Palindromic Subsequence in a given String

Pattern: Strings DP

medium

dp[i][j] counts palindromic subsequences (by positions) inside s[i..j]. By inclusion-exclusion, dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]; if s[i] == s[j], add dp[i+1][j-1] + 1 for those wrapped by the two ends.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return the number of non-empty palindromic subsequences of s, counting by positions (equal strings at different positions count separately). The answer is taken modulo 10⁹ + 7.

Think first

  • How do you avoid counting a subsequence twice when combining the two shorter segments?
  • What do matching ends add?
  • Why +1?

Hints

    Brute force, and why it fails

    Try every subsequence: 2ⁿ.

    The key insight

    Inclusion-exclusion over the two ends counts each palindrome exactly once.

    Dry run

    count3

    'aab': the single characters give 3.

    Step 1 of 2

    The plan

    dp[i][i] = 1
    dp[i][j] = dp[i+1][j] + dp[i][j-1] + (1 if s[i] == s[j] else -dp[i+1][j-1])
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Every segment once.

    Edge cases

    • One character: 1.
    • All equal: 2ⁿ - 1.
    • Large n: modulo, keeping values non-negative.
    I've built my logic, show the code

    Java

    class Solution {
        public int countPS(String s) {
            final long MOD = 1_000_000_007L;
            int n = s.length();
            long[][] dp = new long[n][n];           // dp[i][j]: palindromic subsequences inside s[i..j] (by position)
            for (int i = n - 1; i >= 0; i--) {
                dp[i][i] = 1;
                for (int j = i + 1; j < n; j++) {
                    if (s.charAt(i) == s.charAt(j)) dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] + 1) % MOD;   // plus every inner one wrapped
                    else dp[i][j] = ((dp[i + 1][j] + dp[i][j - 1] - (i + 1 <= j - 1 ? dp[i + 1][j - 1] : 0)) % MOD + MOD) % MOD;   // no double count
                }
            }
            return (int) dp[0][n - 1];
        }
    }

    C++

    class Solution {
    public:
        int countPS(string s) {
            const long long MOD = 1000000007LL;
            int n = static_cast<int>(s.size());
            vector<vector<long long>> dp(n, vector<long long>(n, 0));   // palindromic subsequences inside s[i..j] (by position)
            for (int i = n - 1; i >= 0; i--) {
                dp[i][i] = 1;
                for (int j = i + 1; j < n; j++) {
                    if (s[i] == s[j]) dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] + 1) % MOD;   // plus every inner one wrapped
                    else dp[i][j] = ((dp[i + 1][j] + dp[i][j - 1] - (i + 1 <= j - 1 ? dp[i + 1][j - 1] : 0)) % MOD + MOD) % MOD;   // no double count
                }
            }
            return static_cast<int>(dp[0][n - 1]);
        }
    };

    Python

    class Solution:
        def countPS(self, s: str) -> int:
            MOD = 1_000_000_007
            n = len(s)
            dp = [[0] * n for _ in range(n)]        # dp[i][j]: palindromic subsequences inside s[i..j] (by position)
            for i in range(n - 1, -1, -1):
                dp[i][i] = 1
                for j in range(i + 1, n):
                    if s[i] == s[j]:
                        dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] + 1) % MOD   # plus every inner one wrapped by the ends
                    else:
                        inner = dp[i + 1][j - 1] if i + 1 <= j - 1 else 0
                        dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] - inner) % MOD   # the middle was counted twice
            return dp[0][n - 1]

    Common mistakes

    • Negative values after the modulo.
    • Counting distinct strings instead of positions.

    Similar problems