Count Different Palindromic Subsequences

Hard

Topics
StringDynamic Programming

Given a string s, return the number of different non-empty palindromic subsequences in s, taken modulo 10^9 + 7. Two subsequences are different if there is some index where they differ.

Example 1

b0c1c2b3
Input:  s = "bccb"
Output: 6

Example 2

a0b1c2d3
Input:  s = "abcd"
Output: 4

Example 3

a0a1a2
Input:  s = "aaa"
Output: 3

Constraints

  • 1 <= s.length <= 12
  • s consists of characters 'a', 'b', 'c', or 'd'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Counting distinct palindromic subsequences, not occurrences, is what makes this hard: the usual interval DP would count the same string many times over. The fix is to organise the count by the palindrome's outer character.

For an interval with s[i] != s[j], inclusion-exclusion over the two sub-intervals is enough. When s[i] == s[j] == c, every palindrome inside can be used bare or wrapped in c ... c, giving 2 × inner, and then the single-character c and the pair cc are added — unless c already occurs inside, in which case those were already counted and the overlap must be subtracted. The three cases (no c inside, exactly one, two or more) are exactly that bookkeeping.

Approach

  1. Seed dp[i][i] = 1: a single character is one palindrome.
  2. Grow by interval length. If the ends differ, dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1].
  3. If the ends match, scan inward for the first and last occurrence of that character strictly inside.
  4. No occurrence: 2·dp[i+1][j-1] + 2. Exactly one: 2·dp[i+1][j-1] + 1. Two or more: 2·dp[i+1][j-1] - dp[lo+1][hi-1].
  5. Take the result modulo 10⁹+7, adding the modulus first so a negative intermediate is normalised.

Dry Run

s = "bccb"

  interval  text    dp  reasoning
  [i,i]     any     1   a single character
  [0,1]     "bc"    2   ends differ: 1 + 1 - 0
  [1,2]     "cc"    2   ends match, no c inside: 2*0 + 2
  [2,3]     "cb"    2   ends differ: 1 + 1 - 0
  [0,2]     "bcc"   3   ends differ: 2 + 2 - 1
  [1,3]     "ccb"   3   ends differ: 2 + 2 - 1
  [0,3]     "bccb"  6   ends match, no b inside: 2*2 + 2

answer 6 -- the six are b, c, cc, bb, bcb, bccb

Complexity

  • Time — O(n²): there are O(n²) intervals. The inward scans are not O(1), so this deserves a second look — and the bound survives. For a fixed character, the scan from i costs the gap to the next occurrence, and summing over all pairs gives (occurrences × n); summing that over a four-letter alphabet is O(n²). Measured scan steps stay at roughly 0.73·n² as n goes from 100 to 400, flat rather than growing. Precomputing next and previous occurrence tables makes it O(n²) unconditionally, independent of alphabet size.
  • Space — O(n²) for the table.

Common Pitfalls

  • Counting occurrences rather than distinct strings. The 2×-and-adjust structure exists purely to deduplicate; a plain palindrome-counting DP answers a different question.
  • Forgetting the modulus normalisation. The - dp[lo+1][hi-1] branch can go negative after an earlier modulo, so ((x % M) + M) % M is required, not decorative.
  • Taking the modulus only at the end. The intermediate products overflow in a fixed-width language long before the final value is reached.
  • Collapsing the one-occurrence and many-occurrence cases. They differ by exactly the double-count of cc, and merging them is off by one per interval.
  • Assuming the four-letter alphabet is incidental. It is what keeps the inward scans amortised; the same code on a large alphabet still runs, but the O(n²) argument above needs the occurrence tables instead.
  • Brute-forcing subsets. At the stated bound of 12 characters that is only 4,096 masks and it passes — worth saying out loud as the baseline, but it is exponential and the interval DP is the answer being examined.

Full Solution — all languages

class Solution:
    def countPalindromicSubsequences(self, s):
        MOD = 1000000007
        n = len(s)
        if n == 0:
            return 0
        dp = [[0] * n for _ in range(n)]
        for i in range(n):
            dp[i][i] = 1
        for length in range(2, n + 1):
            for i in range(0, n - length + 1):
                j = i + length - 1
                if s[i] != s[j]:
                    dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]
                else:
                    lo = i + 1
                    hi = j - 1
                    while lo <= hi and s[lo] != s[i]:
                        lo += 1
                    while lo <= hi and s[hi] != s[i]:
                        hi -= 1
                    if lo > hi:
                        dp[i][j] = dp[i + 1][j - 1] * 2 + 2
                    elif lo == hi:
                        dp[i][j] = dp[i + 1][j - 1] * 2 + 1
                    else:
                        dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]
                dp[i][j] = ((dp[i][j] % MOD) + MOD) % MOD
        return dp[0][n - 1]
SensAI
Beta
Tap the mic to stop voice mode