HardStringDynamic Programming

Count Different Palindromic Subsequences

1 approach, code in every language

Problem description

You are given a string `s`. Count the number of distinct non-empty subsequences of `s` that read the same forwards and backwards. Because this total can be enormous, return it modulo `10^9 + 7`.

A subsequence is formed by deleting zero or more characters while preserving order. Two palindromic subsequences are considered the same if the resulting strings are identical, regardless of which positions were selected, so only unique strings should be counted.

Example 1

Input: s = "bccb"

Output: 6

The distinct palindromic subsequences are `b`, `c`, `bb`, `cc`, `bcb`, and `bccb`. The two ways of selecting `bb` count only once.

Example 2

Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"

Output: 104860361

The raw count is astronomically large, so the answer is reduced modulo 10^9 + 7.

Constraints

  • 1 <= s.length <= 1000
  • s consists of only the characters 'a', 'b', 'c', or 'd'.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free