Version: v1.6.5 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2021 License: MIT Imports: 0 Imported by: 0


< Previous                  Next >

730. Count Different Palindromic Subsequences (Hard)

Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo 10^9 + 7.

A subsequence of a string S is obtained by deleting 0 or more characters from S.

A sequence is palindromic if it is equal to the sequence reversed.

Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i.

Example 1:

S = 'bccb'
Output: 6
The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.

Example 2:

S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
Output: 104860361
There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.


  • The length of S will be in the range [1, 1000].
  • Each character S[i] will be in the set {'a', 'b', 'c', 'd'}.
  • [String] [Dynamic Programming]

    Similar Questions

    1. Longest Palindromic Subsequence (Medium)


    Hint 1 Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form "a_a", "b_b", "c_c", and "d_d", where "_" represents zero or more characters.


    The Go Gopher

    There is no documentation for this package.

    Jump to

    Keyboard shortcuts

    ? : This menu
    / : Search site
    f or F : Jump to
    t or T : Toggle theme light dark auto
    y or Y : Canonical URL