Count Different Palindromic Subsequences

Hard

Topics
StringDynamic Programming

Given a string s, count the different non-empty palindromic subsequences it contains. Two subsequences are different when the strings they spell differ, so the same string reached by different positions counts once.

Return the count modulo 10^9 + 7.

Example 1

inputb0c1c2b3
distinct palindromesbcbbccbcbbccb
one distinct palindrome
This string of 4 characters spells 10 distinct subsequences in all, and 6 of them read the same both ways — the chips, which are the answer. A subsequence keeps the order but may skip characters, so these need not be contiguous. They are counted by the string spelled, not by the positions chosen, so a palindrome reachable from several different positions still counts once.
The empty subsequence is not counted, and the published answer is taken modulo 10^9 + 7.
Input:  s = "bccb"
Output: 6
Explanation: The distinct palindromes are b, c, bb, cc, bcb and bccb. "b" counts once even though either of the two b positions could supply it, which is what "different" means here.

Example 2

inputa0b1c2d3
distinct palindromesabcd
one distinct palindrome
Input:  s = "abcd"
Output: 4
Explanation: Only the four single characters are palindromes.

Example 3

inputa0a1a2
distinct palindromesaaaaaa
one distinct palindrome
Input:  s = "aaa"
Output: 3
Explanation: The distinct palindromes are a, aa and aaa — three, not seven, because identical strings collapse.

Constraints

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls

Intuition

The word different is the entire difficulty. Counting palindromic subsequences by position is a short recurrence; counting them by the string they spell means that "aaa" contributes a, aa and aaa rather than seven, and every method has to avoid recounting the same string from different positions.

The way to make distinctness automatic is to organise the count by the outermost character. A palindrome inside s[i..j] that begins and ends with the letter c is determined by that letter plus a palindrome strictly inside the first and last occurrence of c in that range. Choosing the first and last occurrence rather than any pair is what removes the duplicates.

For a fixed range and a fixed letter c, let lo be the first position of c in the range and hi the last. If there is no c, it contributes nothing. If lo == hi, the only palindrome is c itself. Otherwise the contributions are c, cc, and c + any palindrome inside (lo, hi) + c.

Summing that over all 26 letters for every range gives the answer, and because each palindrome is attributed to exactly one letter and one range, nothing is double counted.

Approach

  1. Let count(i, j) be the number of distinct non-empty palindromic subsequences of s[i..j].
  2. For each of the 26 letters, find the first and last occurrence inside [i, j].
  3. If the letter is absent, it adds nothing. If it occurs once, it adds 1, for the single character.
  4. Otherwise it adds 2 + count(lo + 1, hi - 1), for the single character, the doubled character, and each inner palindrome wrapped in that letter.
  5. Sum over the letters, reduce modulo 10^9 + 7, and memoise by (i, j).
  6. Prefix tables of each letter’s next and previous occurrence make the first and last lookups constant time.

Walkthrough

s = "bccb"

count(0,3) over the letters present

   letter b: first at 0, last at 3, different
      contributes b, bb, and b + count(1,2) + b
      count(1,2) is over "cc":
         letter c: first 1, last 2, different
            contributes c, cc, and c + count(2,1) + c
            count(2,1) is an empty range -> 0
         so count(1,2) = 2        { c, cc }
      so b contributes 2 + 2 = 4  { b, bb, bcb, bccb }

   letter c: first at 1, last at 2, different
      contributes c, cc, and c + count(2,1)=0 + c
      = 2                        { c, cc }

total 4 + 2 = 6

and the six are: b, c, bb, cc, bcb, bccb

why first-and-last and not any pair
   in "aaa", the pairs (0,1), (0,2), (1,2) would each
   produce "aa". Fixing the outer letter to its FIRST
   and LAST occurrence in the range makes "aa" arise
   exactly once.

Complexity

  • Time — O(n^2 * 26): each of the n^2 ranges sums over the alphabet, with constant-time first and last lookups.
  • Space — O(n^2): the memo table over ranges dominates. The recursion adds a call stack as deep as the range shrinks, so O(n) frames, which the n^2 table swallows — but say it out loud in an interview rather than leaving the stack unaccounted for.

Common Pitfalls

  • Counting by position instead of by string, which overcounts badly: "aaa" gives 7 rather than 3.
  • Pairing any two occurrences of the outer letter rather than the first and the last, which produces the same palindrome more than once.
  • Forgetting that a letter occurring once still contributes the single character.
  • Dropping the modulus inside the recursion and only applying it at the end.
  • Treating the empty subsequence as a palindrome. The count is over non-empty ones.

Full Solution — all languages

class Solution:
    def countPalindromicSubsequences(self, s):
        from functools import lru_cache

        MOD = 10 ** 9 + 7
        n = len(s)

        @lru_cache(maxsize=None)
        def count(i, j):
            if i > j:
                return 0

            total = 0
            for c in set(s[i:j + 1]):
                lo = s.index(c, i, j + 1)
                hi = s.rindex(c, i, j + 1)

                if lo == hi:
                    total += 1                      # just "c"
                else:
                    # "c", "cc", and c + (each inner palindrome) + c
                    total += 2 + count(lo + 1, hi - 1)

            return total % MOD

        return count(0, n - 1)
SensAI
Beta
Tap the mic to stop voice mode