HardStringDynamic Programming

Count Different Palindromic Subsequences

LeetCode
1 approach, code in all languages

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'.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now