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 <= 1000s consists of only the characters 'a', 'b', 'c', or 'd'.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI